我必须编写一个C程序,它读取一系列整数(正、负或零),并且只计算正整数的平均值。
如果没有正数,您应该在下面的语句后面显示一个新行
没有正数!
这是我的代码,我只需要帮助如何忽略输入序列中的负数。
#include<stdio.h>
int main(){
int num; //number of elements
int i;
int sequence[100]; //numeber if sequence
int sum = 0.0; //sum if the sequence
float avg; // the average
printf("Enter the number of number in the sequence:\n");
scanf("%d", &num);
while (num < 0 || sequence[num] < 0) {
printf("No positine numbers!\n");
}
printf("Enter the sequence:\n");
for (i=0; i < num; i++) {
scanf("%d", &sequence[i]);
sum += sequence[i];
}
avg = (float) sum / num;
printf("Average is %.2f\n", avg);
return(0);
}
最佳答案
代码中存在多个问题:sequence[num]
可以引用数组末尾以外具有未定义行为的项,或者从具有未定义行为的未斜体数组读取。完全删除这个测试,因为它是无用的。
您不需要存储读取的数字,只需将它们一次一个地读入一个临时变量,并且只添加和计数正值。
您应该测试scanf
的返回值,以避免在无效输入上出现未定义的行为。
以下是更正和简化版本:
#include <stdio.h>
int main() {
int num; // max number of values to read
int count = 0; // number of positive values
double sum = 0.0; // sum if the sequence
double avg; // the average
printf("Enter the number of number in the sequence:\n");
if (scanf("%d", &num) == 1 && num > 0) {
printf("Enter the sequence:\n");
while (num-- > 0) {
int temp;
if (scanf("%d", &temp) != 1)
break;
if (temp >= 0) {
sum += temp;
count++;
}
}
avg = sum / count;
printf("Average is %.2f\n", avg);
}
return 0;
}
关于c - 在c中的数字序列中查找平均值,而忽略序列中的负数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53290617/