你知道为什么这段代码偏偏第七个数字是个垃圾数吗?


#include 
#define MONTH 12
#define YEARS 5
void maverage (float arr1[MONTH] , float (*arr2)[MONTH]);
void yaverage (float arr1[YEARS] , float (*arr2)[MONTH]);
//用VLA
void showit(float *arr1 , int num);
int main(void)
{
    float monaver[MONTH];//每月平均
    float yearaver[YEARS];//每年平均
    //float averagemon;
    //float averageyear;
    float allyear;
    const float rain[YEARS][MONTH]=  {
        {4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
        {8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3},
        {9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4},
        {7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2},
        {7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2},
    };
    
    printf(" Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  ");
    printf(" Nov  Dec\n");//%4.1f;
    maverage(monaver , rain);
    //showit(monaver , MONTH);
    
    return 0;
}

void maverage (float arr1[MONTH] , float (*arr2)[MONTH])
{
    float subit[MONTH];
    int i , j;
    
    for(i = 0 ; i < MONTH  ; i++)
    {
        for(j = 0 ; j < YEARS ; j++)
        {
            subit[i] += arr2[j][i];
        }
        //arr1[i] = subit[i] / YEARS;
    printf("%4.1f " , subit[i] / YEARS);
    }
}

为什么这段代码偏偏第七个数字是个垃圾数?其余全部都是没问题的呢?

应该是因为maverage()函数的subit数组没有初始化,把subit初始化下就可以了,修改如下:


 
#include <stdio.h>
#define MONTH 12
#define YEARS 5
void maverage (float arr1[MONTH] , const float (*arr2)[MONTH]);
void yaverage (float arr1[YEARS] , const float (*arr2)[MONTH]);
//用VLA
void showit(float *arr1 , int num);
int main(void)
{
    float monaver[MONTH];//每月平均
    float yearaver[YEARS];//每年平均
    //float averagemon;
    //float averageyear;
    float allyear;
    const float rain[YEARS][MONTH]=  {
        {4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},
        {8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3},
        {9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4},
        {7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2},
        {7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2},
    };
    
    printf(" Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  ");
    printf(" Nov  Dec\n");//%4.1f;
    maverage(monaver , rain);
    //showit(monaver , MONTH);
    
    return 0;
}
 
void maverage (float arr1[MONTH] , const float (*arr2)[MONTH])
{
    float subit[MONTH]={0};
    int i , j;
    
    for(i = 0 ; i < MONTH  ; i++)
    {
        for(j = 0 ; j < YEARS ; j++)
        {
        //    printf("%.2f ",arr2[j][i]);
            subit[i] += arr2[j][i];
        }
       
        
        arr1[i] = subit[i] / YEARS;
        printf("%4.1f " , subit[i] / YEARS);
    }
}

img

第34行:float subit[MONTH] = {0}; //数组 subit[MONTH] 没有初始化