这是我的代码,它正在工作,但它只打印最小值并将其打印为负数。这段代码出了什么问题?
#include <stdio.h>
int main(void) {
double x[5][5],Max, Min;
int i, j;
for (i = 0; i<5; i++)
{
for (j = 0; j<5; j++)
scanf("%lf", &x[i][j]);
}
Max = x[0][0];
Min = x[0][0];
if (x[i][j] > x[0][0])
printf("Max= %f\n", x[i][j]);
else if (x[i][j] < x[0][0])
printf("Min = %f\n", x[i][j]);
return 0;
}
答案 0 :(得分:4)
接收输入后,您永远不会遍历数组,因为您位于for
循环之外。你可以这样做:
Max = x[0][0];
Min = x[0][0];
for(i = 0; i < 5; ++i)
{
for(j = 0; j < 5; ++j)
{
if (x[i][j] < Min) // Is current element smaller than Min?
Min = x[i][j]; // If so, update Min
if (x[i][j] > Max) // Is current element greater than Max?
Max = x[i][j]; // If so, update Max
}
}
printf("Max= %f\n", Max);
printf("Min= %f\n", Min);
答案 1 :(得分:1)
你忘了在循环中附上最小值和最大值的搜索。:)
尝试以下
for (i = 0; i<5; i++)
{
for (j = 0; j<5; j++)
scanf("%lf", &x[i][j]);
}
Max = x[0][0];
Min = x[0][0];
for (i = 0; i<5; i++)
{
for (j = 0; j<5; j++)
{
if ( Max < x[i][j] )
{
Max = x[i][j];
}
else if ( x[i][j] < Min )
{
Min = x[i][j];
}
}
}
printf( "Max = %f\n", Max );
printf( "Min = %f\n", Min );
答案 2 :(得分:0)
您需要遍历2D数组中的所有值以检查2D数组的所有值,并相应地设置max
和min
变量:
Max = x[0][0]; //set max as the first element
Min = x[0][0]; //set min as the first element
for (i = 0; i<5; i++) //loop through each row
{
for (j = 0; j<5; j++) //loop through each column
{
if (x[i][j] > Max) //if current value is more than max
Max=x[i][j];
if (x[i][j] < Min) //if current value is less than min
Min=x[i][j];
}
}
printf("Max= %f\n", Max);
printf("Min = %f\n", Min);