2017-05-28 21 views
0

我有這個代碼我試圖找到矩陣中的數字模式,但模式部分的輸出始終爲0,即使矩陣有沒有零號碼。不過,我不確定如何去做這件事。這是我迄今爲止。如何找到矩形矩陣中的一組數字的模式

#include <stdio.h> 
#include <math.h> 

int mode(int a[],int n) { 
    int maxValue = 0, maxCount = 0, i, j; 

    for (i = 0; i < n; ++i) { 
     int count = 0; 
     for (j = 0; j < n; ++j) { 
      if (a[j] == a[i]) 
       ++count; 
     } 

     if (count > maxCount) { 
      maxCount = count; 
      maxValue = a[i]; 
     } 
    }   
    return maxValue; 
} 

int main(){ 
    int row, column,mat[100][100],maximum=0,minimum,sum =0,a=0,n=0,i, j;// int i and j are loop variables 
    float Average,x; 
    printf("Enter number of rows (between 1 and 100): "); 
    scanf("%d", &row); 
    printf("Enter number of columns (between 1 and 100): "); 
    scanf("%d", &column); 

    printf("\nEnter elements of the matrix:\n"); 

    for(i=0; i<row; ++i) 
     for(j=0; j<column; ++j) 
     { 
      printf("Enter element a%d%d: ",i+1,j+1); 
      scanf("%d",&mat[i][j]); 
     } 
     printf("\n\nThe elements in the matrix are: \n\n") ; 
     for(i = 0 ; i < row ; i++){ 
      for(j = 0 ; j < column ; j++){ 
       printf("%d", mat[i][j]) ;//displays the square matrix 
       printf("\t"); 
      } 
     printf("\n"); 
    } 
    for(i=0; i<row; ++i) 
     for(j=0; j<column; ++j){ 
      if (mat[i][j] < minimum){ 
       minimum = mat[i][j]; 
      } 
      if (mat[i][j] > maximum){ 
       maximum = mat[i][j]; 
      } 
      sum = sum + mat[i][j]; 
      x = row * column; 
      Average = sum /x; 
     } 
    printf("Maximum element in the matrix is %d\n", maximum); 
    printf("Minimum element in the matrix is %d\n", minimum); 
    printf("The sum of the elements in the matrix is %d\n",sum); 
    printf("The average of the elements in the matrix is %.4f\n",Average); 
    printf("Mode = %d ", mode(a,n)); 

    return 0; 
} 

輸出應該是這樣的:

Enter number of rows (between 1 and 100): 3 
Enter number of columns (between 1 and 100): 3 

Enter elements of the matrix: 
Enter element a11: 4 
Enter element a12: 4 
Enter element a13: 4 
Enter element a21: 5 
Enter element a22: 6 
Enter element a23: 7 
Enter element a31: 8 
Enter element a32: 9 
Enter element a33: 0 


The elements in the matrix are: 

4  4  4 
5  6  7 
8  9  0 
Maximum element in the matrix is 9 
Minimum element in the matrix is 0 
The sum of the elements in the matrix is 47 
The average of the elements in the matrix is 5.2222 
Mode = 4 
+0

1)格式化這種混亂。 2)學習[問]並提供必要的信息。 3)調試器是你的朋友。 – Olaf

+0

你用'int a = 0;'聲明'a'爲int,然後把它傳遞給你的函數(不需要在任何地方調整這個值):'mode(a,n)',但是那個函數需要一個' int *'作爲第一個參數(不要緊,你稱它爲'a'也是)。 –

+0

另外,你正在計算'x = row *列; Average = sum/x;'爲數組中的每個元素。將它移到兩個嵌套循環之外。 –

回答

1

的參數應該是一個矩陣,而不是一個整數變量i假設

printf("Mode = %d ", mode(a,n));