gpt4 book ai didi

在 C 中正确使用 scanf(),输出错误

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

我正在尝试设计一个程序来计算任何所需数量的 float 的平均值,直到 EOF。该程序还应检查输入是否正确,并在例如输入错误时返回“错误输入”。输入一个字符串。我编写的代码有效,但它给出了错误的平均值输出。谁能告诉我为什么?

#include <stdio.h>

int main(void) {
int times = 0;
float sum = 0;
float scan;
float avrg;
int scanvalue = 1;
while (scanvalue == 1) {
scanvalue = scanf("%f", &scan);
sum = sum + scan;
times++;
}
if (scanvalue == EOF) {
avrg = sum / times;
printf("The average is %f\n", avrg);
} else {
printf("Wrong input");
}
return 0;
}

最好的问候。

最佳答案

您在 scanf() 之后不检查 scanvalue 并且仍然使用 scan 时的值,这会弄乱平均值。请注意,当 scanf() 返回 EOF 时,它不会修改 scan,因此它仍将具有其最后一个值,因此您添加的是最后一个值(value)两倍。

但是如果你在开头输入了无效的输入那么行为是未定义的,把它改成

while ((result = scanf("%f", &value)) == 1) {
}

另外,我特意更改了变量的名称,以说明更好的命名方式。

关于在 C 中正确使用 scanf(),输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42388786/

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