所以我有这个程序接受一个整数(i),然后制作一个2D数组i x i和那部分我可以正常工作,但现在我试图找到数组中的最小数字,这总是返回0。
int smallest_number(int b[MAXrow][MAXcol], int n)
{
int min = b[0][0];
int x,y;
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
{
if (min > b[x][y])
{
min = b[x][y];
}
}
}
return min;
}
你过早地返回“min”变量。目前,它处于外循环中。你想要的是让它在另一个循环之外。
像这样:
int smallest_number(int b[MAXrow][MAXcol], int n)
{
int min = b[0][0];
int x,y;
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
{
if (min > b[x][y])
{
min = b[x][y];
}
}
}
return min;
}
You can try code below to find maximum & minimum from a matrix of any order.
Code :
#include<stdio.h>
void acc(int [5][5],int,int );
void maxmin(int [5][5],int,int);
void main()
{
int a[5][5],r,c;
printf("\n\t\t**Smallest & largest no. from matrix**\n");
printf("\n\tEnter the size of row:\n\t");
scanf("%d",&r);
printf("\tEnter the size of column:\n\t");
scanf("%d",&c);
acc(a,r,c);
maxmin(a,r,c);
}
void acc(int m[5][5],int r,int c)
{
int i,j;
printf("\n\tenter the elements of matrix\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\telement[%d][%d]= ",i,j);
scanf("%d",&m[i][j]);
}
}
}
void maxmin(int m[5][5],int r, int c)
{
int max=m[0][0], min=m[0][0],i,j;
for (i=0; i<r; i++)
{
for (j=0; j<c; j++)
{
if(m[i][j]>max)
max= m[i][j];
if(m[i][j]<min)
min= m[i][j];
}
}
printf("\n\tGreatest no. is : %d\n",max);
printf("\n\tSmallest no. is : %d\n",min);
}