下面的程序应该输出
$ ./a.out
Enter real numbers, up to 20, q to quit
10 37 15 21 18 q
You entered the following values:
10.0 37.0 15.0 21.0 18.0
The values have mean 20.2, max 37.0, and min 10.0
$ ./a.out
Enter real numbers, up to 20, q to quit
q
No valid numbers entered
$ ./a.out
Enter real numbers, up to 20, q to quit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
You entered the following values:
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0
15.0 16.0 17.0 18.0 19.0 20.0
The values have mean 10.5, max 20.0, and min 1.0
当我运行我的代码时,我得到了
$ ./a.out
Enter real numbers, up to 20, q to quit
10 37 15 21 18 q
You entered the following values:
10.0 37.0 15.0 21.0
The values have mean 20.8, max 37.0, and min 10.0
所以代码会删除一个数字。
#include <stdio.h>
int main (){
float arr[20];
int i,j;
float mean, min,max,sum=0;
printf("Enter real numbers, upto 20, q to quit : ");
for(i=0;i<20;i++){
scanf("%f",&arr[i]);
if(arr[i]==0){
i--;
break;
}
}
if(i>0){
printf("You entered the following values : \n");
for(j=0;j<i;j++){
printf("%.1f ",arr[j]);//to print values upto 1 decimal
}
//finding mean = sum of numbers /no.of numbers
for(j=0;j<i;j++){
sum = sum + arr[j];
}
mean = sum/i;//finding min and max :
min = arr[0];
max = arr[0];
for(j=1;j<i;j++){
if(arr[j]>max){
max = arr[j];
}
if(arr[j]<min){
min = arr[j];
}
}
printf("\n The values have mean %.1f, max %.1f, and min %.1f",
mean,max,min);
}
else
printf("\nNo valid numbers entered");
}
答案 0 :(得分:1)
scanf
无法按照您的想法运作。使用此:
for(i=0;i<20;i++) {
if(scanf("%f", &arr[i]) != 1)
break;
}
来自文档:
成功时,该函数返回成功填充的参数列表的项目数。
因此,如果它返回0,则它没有成功读取浮点数,这是在输入字符时预期的。