gpt4 book ai didi

c - 这段代码有问题吗?有时我会得到正确答案,有时会得到一个非常大的数字

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:47 26 4
gpt4 key购买 nike

有时我会得到正确的答案,比如当我输入 873 时,它会返回 261,但是当我退出程序并重新运行时它有时会返回 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));
}

最佳答案

程序有未定义的行为,因为局部变量 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;
}

关于c - 这段代码有问题吗?有时我会得到正确答案,有时会得到一个非常大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56956953/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com