我的二维数组中数字的频率输出不正确

时间:2018-10-17 03:17:39

标签: c arrays multidimensional-array

我的目标是,例如,如果我将数组的大小设为2x6,并为第1行输入值(0、1、2、3、4、5)和值(0、1、6、7, 8、9)对于第2行,它将输出: 数字0出现2次 数字1出现2次 数字2出现1次 等等 但事实并非如此。 这是我的代码:

#include <stdio.h>

int main(void)
{
 int row, col, N, M, count, row1, col1;

 printf("This program counts occurrences of digits 0 through 9 in an NxM array.\n");
 printf("Enter the size of the array (Row Column): ");
 scanf("%d %d", &N, &M);

 int digits[N][M], freq[N][M];

 for (row = 0; row < N; row++){ 
  printf("Enter row %d: ", row);
  for (col = 0; col < M; col++){
   scanf("%d", &digits[row][col]);
  }
 } 

 freq[row][col] = -1;

 for (row = 0; row < N; row++){
  count = 1;
  for (row1 = row + 1; row1 < N; row1++){
   for (col = 0; col < M; col++){
    for (col1 = col + 1; col1 < M; col1++){
     if (digits[row][col] == digits[row1][col1]){
      count++;
      freq[row1][col1] = 0;
     }
    }
    if (freq[row][col] != 0){
     freq[row][col] = count;
    }
   } 
  } 
 }

 printf("Total counts for each digit:\n");
 for (row = 0; row < N; row++){
  for (col = 0; col < M; col++){
   if (freq[row][col] != 0){
    printf("Digit %d occurs %d times\n", digits[row][col], freq[row][col]);
   }
  } 
 } 

 return 0;
}

1 个答案:

答案 0 :(得分:2)

我认为第二个循环没有计算您的期望值,为什么不尝试这样的事情:

#include <stdio.h>

int main(void)
{
 int row, col, digit, N, M, currentValue;

 printf("This program counts occurrences of digits 0 through 9 in an NxM array.\n");
 printf("Enter the size of the array (Row Column): ");
 scanf("%d %d", &N, &M);

 int digits[N][M], freq[10] = { 0 };

 for (row = 0; row < N; row++){ 
  printf("Enter row %d: ", row);
  for (col = 0; col < M; col++){
   scanf("%d", &currentValue);
   digits[row][col] = currentValue;
   if (currentValue >= 0 && currentValue <=9) {
     freq[currentValue]++;
   }
  }
 } 

 printf("Total counts for each digit:\n");
 for (digit = 0; digit < 10; digit++){
   if (freq[digit] != 0){
    printf("Digit %d occurs %d times\n", digit, freq[digit]);
   }
 } 

 return 0;
}