我有这个代码我试图找到矩阵中数字的模式,但模式部分的输出总是为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)
参数应该是矩阵而不是整数变量,我想
printf("Mode = %d ", mode(a,n));