c - 如何防止系统将标记值作为输入?
问题描述
所以,我创建了一个简单的程序供用户输入温度并计算最高、最低、平均值。在用户输入哨兵值停止循环后,不知何故哨兵值也会被当作输入并弄乱数据,这是我的代码,如果你有时间请帮我看看,非常感谢
#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);
}
仍然存在一些错误,如果您根本不输入温度,程序将无法正常运行。但我让你自己。应该不会太难。
推荐阅读
- c - c中的数组函数/追加/删除基本
- java - 线程性能建议
- git - 子模块移动后合并冲突
- python - 连接 1 行数据帧时的 Pandas 索引行为
- mysql - 客户从相应列输入值时如何显示MySQL行?
- documentation - 如何使用 Doxygen 生成变更日志?
- machine-learning - 如何使用 to_categorical 将 [[4,7,10],[10,20,30]] 转换为一种热编码
- amazon-web-services - 从 localhost 连接时 AWS RDS 很慢
- gcc - 为什么 gcc -O3 自动矢量化阶乘?那么多额外的指令看起来更糟
- git - How to remove a file from pull request/commit?