请用c语言写出用户输入温度,统计总数以及低于零度数据所占百分比所需代码
时间: 2024-05-07 07:15:24 浏览: 8
```c
#include <stdio.h>
int main() {
int count = 0; // 计数器,记录输入的数据总数
int less_than_zero_count = 0; // 计数器,记录低于零度的数据个数
float temperature; // 存放用户输入的温度值
printf("请输入温度值(输入-999结束输入):\n");
while (1) {
scanf("%f", &temperature);
if (temperature == -999) { // 输入-999结束输入
break;
}
count++; // 计数器加一
if (temperature < 0) { // 如果输入值小于零
less_than_zero_count++; // 计数器加一
}
}
printf("总共输入了%d个温度值。\n", count);
printf("低于零度的温度值占总温度值的%.2f%%。\n", (float)less_than_zero_count / count * 100);
return 0;
}
```
说明:
1. 程序首先定义了两个计数器变量`count`和`less_than_zero_count`,分别用来记录输入的数据总数和低于零度的数据个数。
2. 然后通过一个`while`循环,不断读入用户输入的温度值。当用户输入-999时,结束输入。
3. 在循环中,每读入一个温度值,计数器`count`就加一。如果温度值小于零,计数器`less_than_zero_count`也加一。
4. 最后输出总共输入的温度值和低于零度的温度值占总温度值的百分比。需要注意的是,计算百分比时需要将`less_than_zero_count`转换成`float`类型,否则会得到整数结果。