#include <stdio.h>
float aver(float*,int);
float max = 0, min = 0; // define global variables
int main()
{
int i;
float num[10]; //input number
for (i = 0 ; i < 10 ; i++)
scanf("%f", &num[i]);
printf("%.2f %.2f %.2f ", max, min, aver(num, i)); //output max ,min and aver
return 0;
}
float aver(float*num,int n)
{
max = min = num[0];
int i;
float sum=0;
for (i=0; i<n-1; i++) {
if (max < num[i])
max = num[i]; //find max
else if (min > num[i])
min = num[i]; //find min
sum += num[i];
}
printf("%.2f %.2f \n ",max,min); //output the max and the min in the array num
return sum/n;
}
<小时/>
这是我输入并得到的内容。
1 2 3 4 5 6 7 8 9 10
9.00 1.00
0.00 0.00 4.50 Program ended with exit code: 0
为什么aver
函数中的max
和min
可以正确输出,而在main
函数中他们是0
?
最佳答案
函数参数的求值顺序未指定。因此,您的代码可能在某些编译器上按预期工作,而在其他编译器上可能会产生意外的结果。
你应该更换
printf("%.2f %.2f %.2f ",max,min,aver(num, i)); //output max ,min and aver
与
{
float average = aver(num, i);
printf("%.2f %.2f %.2f ",max,min, average); //output max ,min and aver
}
明确定义代码行为。
<小时/>来自 C99 §6.5.2.2p10:
The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.
关于c - 全局变量输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27962886/