c语言为啥第二次调用函数,,会出现第一次的值,第一次调用会出现乱码,用c++6.0编写的
#include <stdio.h>
int main()
{
float average(float array[],int n,float a[2]);
float a[2];
float score1[]={98.5,97,91.5,60,55}, score2[]={67.5,89.5,99,69.5,77,89.5,76.5,54,60,99.5};
printf("The average of class A is %6.2f the largest is %6.2f the smallest is %6.2f\n",average(score1,5,a),a[0],a[1]);
printf("The average of class B is %6.2f the largest is %6.2f the smallest is %6.2f\n",average(score2,10,a),a[0],a[1]);
return 0;
}
float average(float array[],int n,float a[2])
{
int i;
float aver,sum=array[0];
a[0]=array[0];
a[1]=array[0];
for(i=1;i<n;i++)
{
if(a[0]<array[i])
a[0]=array[i];
if(a[1]>array[i])
a[1]=array[i];
sum=sum+array[i];
}
aver=sum/n;
return (aver);
}
[解决办法]
可能没说明白 就是第一次调用函数average()的时候 a[0],a[1] 里面没有值;他是先输出a[1],然后a[0],在调用函数average(),乱码是因为你的数组没有初始化;同理第二次调用函数average()的时候,存的是前面的a[1]与a[0],所以是第一次调用的值。
[解决办法]
http://digital.cs.usu.edu/~allanv/cs2420/debugger_intro.pdf
[解决办法]
根据C语言标准6.5.2.2.10
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.
average(), a[0], a[1]都是printf()的参数, 它们之间的计算顺序是不能假定的,也就是说你不能因为a[0], a[1]写在了后面就认为是在调用average()后的结果.
[解决办法]
// main函数改成这样吧
//这个结果是和编译器有关系,printf函数不同的编译器参数入栈的顺序是不同的!
#include <stdio.h>
int main()
{
float average(float array[],int n,float a[2]);
float a[2];
float score1[]={98.5,97,91.5,60,55}, score2[]={67.5,89.5,99,69.5,77,89.5,76.5,54,60,99.5};
printf("The average of class A is %6.2f \n",average(score1,5,a));
printf("the largest is %6.2f the smallest is %6.2f\n",a[0],a[1]);
printf("The average of class B is %6.2f \n",average(score2,10,a));
printf("the largest is %6.2f the smallest is %6.2f\n",a[0],a[1]);
return 0;
}