如何解决如何防止系统将前哨值作为输入?
因此,我创建了一个简单的程序供用户输入温度并计算最高,最低,平均值。用户输入哨兵值停止循环后,不知何故哨兵值也将作为输入并弄乱数据,这是我的代码,请帮我看看您是否有空,谢谢!
#include <stdio.h>
int main()
{
int temperature,highest = 0,lowest = 0,counter = 1,counter2 = 0,total = 0;
float average;
printf("Enter temperature (-999 to stop) > ");
scanf("%d",&temperature);
if (temperature == -999) {
printf("No temperature is captured.");
return 0;
}
else if (temperature > 40)
counter2++;
do {
printf("Enter temperature (-999 to stop) > ");
scanf("%d",&temperature);
if (temperature >= highest)
highest = temperature;
if (temperature <= lowest)
lowest = temperature;
if (temperature > 40)
counter2++;
total += temperature;
counter++;
} while (temperature != -999);
average = total / counter;
printf("Total days with temperature more than 40'C > %d\n",counter2);
printf("The lowest temperature > %d\n",lowest);
printf("The highest temperature > %d\n",highest);
printf("Average of temperature > %.2f\n",average);
}
解决方法
您的代码过于复杂。为什么您要从回路中输入第一个温度?第一个输入没有什么特别的。
您想要这样的东西:
#include <stdio.h>
int main()
{
int temperature,highest = 0,lowest = 0,counter = 1,counter2 = 0,total = 0;
float average;
do {
printf("Enter temperature (-999 to stop) > ");
scanf("%d",&temperature);
if (temperature == -999)
break;
if (temperature >= highest)
highest = temperature;
if (temperature <= lowest)
lowest = temperature;
if (temperature > 40)
counter2++;
total += temperature;
counter++;
} while (temperature != -999);
average = total / counter;
printf("Total days with temperature more than 40'C > %d\n",counter2);
printf("The lowest temperature > %d\n",lowest);
printf("The highest temperature > %d\n",highest);
printf("Average of temperature > %.2f\n",average);
}
仍然存在一些错误,如果根本不输入温度,则该程序将无法正常运行。但是我让你自己一个。应该不难。
,您添加了哨兵(-999),因为您在之前添加了值,然后到达了测试哨兵值的代码。您需要立即进行测试。
但是即使已解决,仍然存在更多问题。
您首先将lowest
设置为零,因此,如果我输入20后接-999,那么lowest
仍将为零。
您不保存第一个输入(递增count2
除外),因此最终结果将是错误的。同样,如果我输入20后跟-999,那么total
将为零(假设我们已经解决了哨兵问题)。如果我输入20 40 -999,则total
只会增加40,而平均值将是20,因为count
会增加两次。
此外,您应始终检查scanf
返回值。
因此,您需要重新组织代码。例如:
#include <stdio.h>
int main()
{
int temperature,counter = 0,total = 0;
float average;
printf("Enter temperature (-999 to stop) > ");
if (scanf("%d",&temperature) != 1) exit(1);
if (temperature == -999) {
printf("No temperature is captured.");
return 0;
}
lowest = temperature;
highest = temperature;
do {
if (temperature >= highest)
highest = temperature;
if (temperature <= lowest)
lowest = temperature;
if (temperature > 40)
counter2++;
total += temperature;
counter++;
printf("Enter temperature (-999 to stop) > ");
if (scanf("%d",&temperature) != 1) exit(1);
} while (temperature != -999);
average = total / counter;
printf("Total days with temperature more than 40'C > %d\n",counter2);
printf("The lowest temperature > %d\n",lowest);
printf("The highest temperature > %d\n",highest);
printf("Average of temperature > %.2f\n",average);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。