【问题标题】:Basic C help using arrays and for loops使用数组和 for 循环的基本 C 帮助
【发布时间】:2016-10-14 19:45:10
【问题描述】:
#include "stdafx.h"
#include "stdio.h"
#include <string.h>

void main() {
    int Results[8];
    int i = 0;
    int max = 0;
    int maxindex;

    printf("Enter the results of your 7 leavin cert subjects: ");
    do {
        printf("\nSubject %d: ", i + 1);
        scanf_s("%d", Results);
        i++;
    } while (i < 7);

    for (i < 7; Results[i] > 0; i++)
        if (Results[i] > max)
            max = Results[i];
    printf("The best grade is %d", max);
}

你好,所以基本上我正在尝试使用 for 循环打印出最大的数字(最佳结果)。但是它一直告诉我最好的结果是 0。

有谁知道我做错了什么。任何帮助将不胜感激。

【问题讨论】:

  • 你认为scanf_s("%d", Results) 会做什么?
  • scanf_s("%d", Results); 在每个循环中输入相同的元素 - 索引 0,因为数组标识符衰减为指向第一个元素的指针。
  • 此外,for (i &lt; 7; Results[i]&gt;0; i++) 给出了编译器警告,因为启动条件可能不是您想要的。
  • 我建议你拿出一张纸,创建一个有行有列的表格。在每列的顶部,放置一个变量的名称。对于每一行,仔细检查每一行代码并写下每个变量的值。现在使用调试器查看您的表是否正确。

标签: c arrays for-loop while-loop int


【解决方案1】:

您的代码中有两个主要问题:

  • 您使用scanf_s("%d", Results); 将所有数字读入Results[0]。你应该写:

    if (scanf_s("%d", &Results[i]) != 1) {
        /* not a number, handle the error */
    }
    
  • 第二个循环不正确:for (i &lt; 7; Results[i] &gt; 0; i++) 有多个问题。改写for (i = 0; i &lt; 7; i++)

还有更小的:

  • #include "stdio.h" 应该写成#include &lt;stdio.h&gt;
  • #include "stdafx.h" 未使用,因此可以删除 - 无论如何,如果要使用它应该写成 #include &lt;stdafx.h&gt;
  • Results 数组的大小为 8,但您只使用 7 插槽。
  • main 应该有原型 int main(void)int main(int argc, char *argv[]) 或等效项。
  • 喜欢惯用的 for (i = 0; i &lt; 7; i++) 循环而不是容易出错的 do / while 循环。
  • 为非平凡的循环体使用大括号。

这是一个更简单更好的版本:

#include <stdio.h>
#include <string.h>

int main(void) {
    int Results[7];
    int i, n, max;

    printf("Enter the results of your 7 leavin cert subjects: ");
    for (i = 0; i < 7; i++) {
        printf("\nSubject %d: ", i + 1);
        if (scanf_s("%d", &Results[i]) != 1) {
            printf("invalid number\n");
            exit(1);
        }
    }

    for (n = i, max = 0, i = 0; i < n; i++) {
        if (Results[i] > max)
            max = Results[i];
    }
    printf("The best grade is %d\n", max);

    return 0;
}

【讨论】:

  • 谢谢,我自己更正了结果问题。我真的很感激。
猜你喜欢
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多