声明变量时赋初值,得出正确结果;不赋初值得出错误结果
程序代码:
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ *求方差,公式为[(x1-y)^2+(x2-y)+……]/n,其中xi为所求方差的数字,y为平均值,n为+ *所求方差的数字的个数 + *要求是输入整形数,返回整形数 + *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #include <stdio.h> #include <math.h> //int function(int *calculate[],int arrayLen); int main(void) { int calculate[3]={1,2,3};//输入的数字储存在数组calculate中 int arrayLen=3;//输入数字的个数 printf("%d\n",function(calculate,3)); } int function(int calculate[],int arrayLen) { int i; float sum=0,average=0,square=0,square_average=0; //当sum,average,square,square_average不赋初值得时候,得出的结果是错误的, //为什么会这样?这一点疑惑不解。 for(i=0;i<arrayLen;i++) sum+=calculate[i]; average=sum/arrayLen; for(i=0;i<arrayLen;i++) square_average+=(calculate[i]-average)*(calculate[i]-average); return (int)square_average/arrayLen; }
第23行,当sum,average,square,square_average声明而不赋初值的时候,得出的结果是-715027002,当给它们赋初值之后就会给出正确的结果0,为什么会这样?这一点疑惑不解。