这段代码有问题吗?有时我会得到正确的答案,有时我会得到很多

时间:2019-07-09 16:26:49

标签: c

有时候我得到正确的答案,例如当我输入873时,它会给我261, but when I exit the program and re-run it, sometimes it returns 45481185383493847891312640.000000`或其他一些疯狂的数字。

#include <stdio.h>

int main() {
    float pts = 0;
    float avg;
    float grade;
    float total;
    int f = 1;

    while (f == 1) {
        printf("Choose a Course Grade, and the amount of points that the course is worth: \n"
               "Enter -1 at the beginning if you want to exit\n");
        scanf("%f %f", &grade, &avg);
        if (grade == -1) {
            break;
        }
        pts += avg;
        total += (avg * grade);
        printf("%f\n", total);
    }
    printf("%f\n", (total / pts));
}

1 个答案:

答案 0 :(得分:3)

该程序具有未定义的行为,因为局部变量total未初始化。

将其初始化为0并测试scanf()的返回值,以避免未定义的行为,这解释了您的观察结果。

这是更正的版本:

#include <stdio.h>

int main() {
    float pts = 0.0;
    float total = 0.0;
    float avg;
    float grade;

    for (;;) {
        printf("Enter a Course Grade or -1 to exit: ");
        if (scanf("%f", &grade) != 1 || grade == -1)
            break;
        printf("Enter a the amount of points that the course is worth: ");
        if (scanf("%f", &avg) != 1)
            break
        pts += avg;
        total += avg * grade;
        printf("%f\n", total);
    }
    printf("%f\n", total / pts);
    return 0;
}