[英]calculating min and max of 2-D array in c
This program to calculate sum,min and max of the sum of array elements 该程序计算数组元素之和的总和,最小值和最大值
Max value is the problem, it is always not true. 最大值是问题,始终不正确。
void main(void)
{
int degree[3][2];
int min_max[][];
int Max=min_max[0][0];
int Min=min_max[0][0];
int i,j;
int sum=0;
clrscr();
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("\n enter degree of student no. %d in subject %d:",i+1,j+1);
scanf("%d",°ree[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("\n Student no. %d degree in subject no. %d is %d",i+1,j+1,degree[i][j]);
}
}
for(i=0;i<3;i++)
{
sum=0;
for(j=0;j<2;j++)
{
sum+=degree[i][j];
}
printf("\n sum of degrees of student no. %d is %d",i+1,sum);
min_max[i][j]=sum;
if(min_max[i][j] <Min)
{
Min=min_max[i][j];
}
else if(min_max[i][j]>Max)
{
Max=min_max[i][j];
}
}
printf("\nThe minimum sum of degrees of student no. %d is %d",i,Min);
printf("\nThe maximum sum of degrees of student no. %d is %d",i,Max);
getch();
}
The problem is that you are initialising Min and Max to min_max[0][0] before assigning any values to min_max, so their content is actually undefined. 问题是您在将任何值赋给min_max 之前将Min和Max初始化为min_max [0] [0],因此它们的内容实际上是不确定的。
Put the assignments Min=min_max[0][0]
and Max=min_max[0][0]
AFTER the scanf
calls. 在
scanf
调用之后放入分配Min=min_max[0][0]
和Max=min_max[0][0]
。
The lines 线
printf("\nThe minimum sum of degrees is %d",i,Min);
printf("\nThe maximum sum of degrees is %d",i,Max);
will print the only value of i
, not Min
or Max
. 将仅打印
i
值,而不是Min
或Max
。 Try this instead: 尝试以下方法:
printf("\nThe minimum sum of degrees for %d is %d",i,Min);
printf("\nThe maximum sum of degrees for %d is %d",i,Max);
The line 线
min_max[i][j]=sum;
will always have a value of 2 for j
because it is outside of the for
loop. j
的值始终为2,因为它在for
循环之外。 Also, I'm not clear why you would want to store the partial sum of degrees in the min_max array? 另外,我不清楚您为什么要在min_max数组中存储度的部分和?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.