基本C语言帮助使用数组和for循环


#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);将所有数字读入Results[0]。你应该这样写:

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

还有更小的:

  • #include "stdio.h"应该写成#include <stdio.h>
  • #include "stdafx.h"没有被使用,因此可以被删除-无论如何,如果要使用它,它应该被写为#include <stdafx.h>
  • Results数组的大小为8,但您只使用7插槽。
  • main应该有int main(void)int main(int argc, char *argv[])的原型或同等的。
  • 支持惯用的for (i = 0; i < 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 numbern");
            exit(1);
        }
    }
    for (n = i, max = 0, i = 0; i < n; i++) {
        if (Results[i] > max)
            max = Results[i];
    }
    printf("The best grade is %dn", max);
    return 0;
}

最新更新