for循环添加先前循环的结果

时间:2013-04-13 20:45:51

标签: c arrays for-loop

我制作了一个程序来计算2D数组的频率,我想让它给出每行(每个i)的结果。但是当我添加for循环for(i=0;i<S1;i++)时,它计算第一行右边和第二行的频率,例如它将第一行的频率添加到第二行,依此类推。如何防止它添加频率?有什么建议吗?谢谢:))

编辑:让我的问题更清晰:如果我添加号码{10 20 30 30 30 30 20 30 10}

  

我应该会收到以下结果:

1st row    0-9        0
          10-19       1
          20-29       1
          30-39       1   from the row {10 20 30}
2nd row   0-9         0
          10-19       0
          20-29       0
          30-39       3    from the row {30 30 30}
 3rd row  0-9          0
          10-19        1
          20-29        1
          30-39        1  from the row {20 30 10}
  

而不是获得这些结果我得到

       1st row 

       0-9        0
      10-19       1
      20-29       1
      30-39       1   
    from the row {10 20 30}
    2nd row   0-9         0
              10-19       2
              20-29       2
              30-39       2    from the row {30 30 30}
     3rd row  0-9          0
              10-19        3
              20-29        3
              30-39        3 from the row {20 30 10}




 #include <stdio.h>
 #define   S1      3                                      
 #define   COUNTER 11   
 #define   S2      3              

 int main() {                                                           
   float A[S1][S2];

   int i, j, k, low, high;                              
   int group[COUNTER] = {0,0,0,0,0,0,0,0,0,0,0};  

   for (i = 0; i < S1; i++) {                
     for (j=0; j < S2; j++) {                                               
        scanf("%f", &A[i][j]);                             
     }                                                       
   }  

   for(i=0; i < S1; i++) {
     for(j=0; j < S2; j++) {
       ++ group[(int)(A[0][j] + 0.5 ) / 10];
     }

     printf("\n");                                           
     printf("GROUP     RANGE     FREQUENCY\n\n") ;          
     for(k = 0; k < COUNTER; k++) {                                                       
       low = k * 10;                                      
       if(k == 10)                                          
         high = 100;                                       
       else                                                 
         high = low + 9;                                   
       printf("%2d    %3d to %3d       %d\n",             
               k+1, low, high, group[k]);                 
     }
   }             
   getch();                                                
 }        

1 个答案:

答案 0 :(得分:0)

您需要重新初始化数组,以便在转到下一行时包含所有零。也许这对你有用:

for(i=0; i < S1; i++) {
   memset(group, 0, sizeof(group));
   for(j=0; j < S2; j++) {
      ++ group[(int)(A[0][j] + 0.5 ) / 10];
      // The rest of your code here.

此外,如果您要尝试获取每一行的频率,您是否应该查看存储在A[i][j]而不是A[0][j]的值?