计算c中2-D数组的最小值和最大值

时间:2010-05-18 06:27:40

标签: c arrays multidimensional-array

该程序计算数组元素之和的和,最小和最大值 最大值是问题,它始终不是真的。

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",&degree[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();

}

2 个答案:

答案 0 :(得分:1)

问题是你在为min_max分配任何值之前将Min和Max初始化为min_max [0] [0] ,因此它们的内容实际上是未定义的。

Min=min_max[0][0]来电之后,分配Max=min_max[0][0]scanf

答案 1 :(得分:0)

printf("\nThe minimum sum of degrees is %d",i,Min);
printf("\nThe maximum sum of degrees  is %d",i,Max);

将打印i的唯一值,而不是MinMax。试试这个:

printf("\nThe minimum sum of degrees for %d is %d",i,Min);
printf("\nThe maximum sum of degrees for %d is %d",i,Max);

该行

min_max[i][j]=sum;
对于j

的值始终为2,因为它位于for循环之外。另外,我不清楚你为什么要在min_max数组中存储部分度数?