#include"stdio.h"
int main()
{
int i, j, maxrow = 0, maxcolum = 0, minrow = 0, mincolum = 0;/*定义行变量i,列变量j,最大的值的行和列并初始化,最
小的行和列并初始化*/
int a[3][4];/*定义数组数值*/
int max = a[0][0];/*把0行0列赋给max*/
int min = a[0][0];/*把0行0列赋给min*/
printf("Please input number for a[3][4]:\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
scanf_s("%d",&a[i][j]);
}
printf("\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
printf("%-2d ", a[i][j]);/*打印a[3][4]数组并输出*/
if (j == 4)
printf("\n");/*如果列数为4,换行*/
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; j++)
{
if (a[i][j] > max)
{
max = a[i][j];
maxrow = i;
maxcolum = j;
}
if (a[i][j] < min)
{
min = a[i][j];
minrow = i;
mincolum = j;
}
}
}/*循环比较,先比较0行(i),列(j)循环(0,1,2,3),在比较1(i),列循环(0.1.2.3)*/
printf("max=%d,maxrow=%d,maxcolum=%d\n", max, maxrow+1 , maxcolum+1 );
printf("min=%d,minrow=%d,mincolum=%d\n", min, minrow+1, mincolum+1);
getchar();
return 0;
}
原程序max和min赋值写在整个数组输入赋值值之前,因此其中存放的并不是数组中a[0][0]的值,而是在赋值前的某个值,这个导致出错。可以考虑将max和min的赋值语句写到scanf循环之后。
#include"stdio.h"
int main() { int i, j, maxrow = 0, maxcolum = 0, minrow = 0, mincolum = 0,a[3][4];
printf("Please input number for a[3][4]:\n");
for (i = 0; i < 3; i++) for (j = 0; j < 4; j++) scanf_s("%d",&a[i][j]);
printf("\n"); maxrow=maxcolum=minrow=mincolum=0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) printf("%-2d ", a[i][j]);
printf("\n");
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
if (a[i][j] > a[maxrow][maxcolum] ) { maxrow = i; maxcolum = j; }
else if (a[i][j]<a[minrow][mincolum]) { minrow = i; mincolum = j; } //两个条件是互斥的
}
}
printf("max=%d,maxrow=%d,maxcolum=%d\n",
a[maxrow][maxcolum],maxrow+1,maxcolum+1);
printf("min=%d,minrow=%d,mincolum=%d\n",
a[minrow][mincolum], minrow+1, mincolum+1);
getchar();
return 0;
}