我必须读取 10 个整数,计算每个值的 90%,以倒序打印它们,最后打印我获得的各种值的中间值。
但它不起作用,它只打印零。另一件事是,在我输入 10 个值后,它仍然需要另一个输入才能开始打印。我是 C 的新手,所以我可能犯了一个愚蠢的错误......
#include <stdio.h>
int main ()
{
int n = 10; //number of numbers
float array[10];
for(int i = 0 ; i < n ; i++) {
scanf("%d \n", &array[i] ) ; //read the keyboard input and memorize it in the array
}
for( int i = 9; i > -1 ; i-- ) {
array[i] = array[i]*90.0/100.0; //calculate the 90% of every value
printf("%f \n", array[i]); //prints the values in opposite order
}
float s = 0;
for(int i = 0 ; i < 10 ; i++){
s = s+array[i]; //add up all the values
}
float m =s/n; //calculate the mid value
printf("%f \n",m); //prints it
system("PAUSE");
return 0;
}
最佳答案
这可能是你的问题:
scanf("%d \n", &array[i] ) ; //read the keyboard input and memorize it in the array
array
元素的类型是float
,您被告知scanf
读取一个整数。那里有未定义的行为。试试这个:
scanf("%f \n", &array[i] ) ; //read the keyboard input and memorize it in the array
关于计算数组元素的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21053871/