寻找2个学生的平均值

时间:2019-09-09 08:37:41

标签: c variable-assignment

我正在运行一个程序,用于计算2个学生的平均值。我在运行此程序时遇到麻烦。由于某些原因,它说找不到。这是我第一次使用Visual Studio,我不确定代码是问题还是程序。

请检查是否有错误,并让我知道。

#include <stdio.h>

int main(void)
{
    int firstGrade1;
    int sGrade1;
    int tGrade1;
    int fGrade1;

    int TotalGrade1 = (firstGrade1 + sGrade1 + tGrade1 + fGrade1);
    int AveGrade1 = (TotalGrade1 / 4);

    printf("Please enter Student 1 first grade:\n");
    scanf("%d", &firstGrade1);

    printf("Please enter Student 1 second grade:\n");
    scanf("%d", &sGrade1);

    printf("Please enter Student 1 third grade:\n");
    scanf("%d", &tGrade1);

    printf("Please enter Student 1 fourth grade:\n");
    scanf("%d", &fGrade1);

    int firstGrade2;
    int sGrade2;
    int tGrade2;
    int fGrade2;

    int TotalGrade2 = (firstGrade2 + sGrade2 + tGrade2 + fGrade2);
    int AveGrade2 = (TotalGrade2 / 4);

    printf("Please enter Student 2 first grade:\n");
    scanf("%d", &firstGrade2);

    printf("Please enter Student 2 second grade:\n");
    scanf("%d", &sGrade2);

    printf("Please enter Student 2 third grade:\n");
    scanf("%d", &tGrade2);

    printf("Please enter Student 2 fourth grade:\n");
    scanf("%d", &fGrade2);

    printf("1. Student 1 grades:");
    printf("%d", firstGrade1, sGrade1, tGrade1, fGrade1);
    printf(". Average is ");
    printf("%d\n", AveGrade1);

    printf("2. Student 2 grades:");
    printf("%d", firstGrade2, sGrade2, tGrade2, fGrade2);
    printf(". Average is ");
    printf("%d", AveGrade2);

    system("pause");

    return (0);

}

1 个答案:

答案 0 :(得分:1)

这里

int TotalGrade1 = (firstGrade1 + sGrade1 + tGrade1 + fGrade1);

没有告诉TotalGrade1总是总是这四个变量加起来的值。它将这些变量的当前值之和分配给TotalGrade1。由于这些未初始化,因此是未定义的行为。读完这些值后,将TotalGrade1AveGrade1的计算结果移至,当然TotalGrade2AveGrade2的计算也将移至该值。

此外,请考虑以下打印内容:

printf("%d", firstGrade1, sGrade1, tGrade1, fGrade1);

您要打印四个int,为什么只有一个格式说明符?格式字符串应为"%d %d %d %d"

我建议始终注意编译器的警告。通常,您的编译器应警告您有关错误的printf格式字符串以及使用未初始化的变量的信息。


另一方面,您有很多代码重复。如果您没有两个学生四个年级,但是却有一百个学生每个十年级呢?想象一下代码量,以及工作量复制/粘贴代码的量。相反,请尝试如下操作:

int main(void)
{
    int Grade[2][4]; 
    int AveGrade[2];
    int TotalGrade[2];

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 4; j++) {
            printf("Please enter Student %d j. grade:\n", i + 1, j+1);
            scanf("%d", &Grade[i][j]);
        }

        TotalGrade[i] = 0;
        for (int j = 0; j < 4; j++)
            TotalGrade[i] += Grade[i][j];
        AveGrade[i] = (TotalGrade[i] / 4);
    }

    for (int i = 0; i < 2; i++) {
        printf("%d. Student %d grades:", i+1, i+1);
        for (int j = 0; j < 4; j++)
        printf("%d ", Grade[i][j]);
        printf(". Average is ");
        printf("%d\n", AveGrade[i]);
    }

    system("pause");
    return (0);
}