c语言 - 从二维数组中查找最大值,将最大值之前的所有值相加,然后将最大值后的所有值相乘



这是我的代码

#include<stdio.h>
void main() {
  int a[4][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 15, 6, 5 },
      { 4, 3, 2, 1 } };
  int max = a[0][0];
  int mIndexF, mIndexE, addition = 0, multiplication = 1, i, j, status = 0, k,
      l;
  // this is for find out maximum value
  for (i = 0; i < 4; i++) {
    for (j = 0; j < 4; j++) {
      if (max < a[i][j]) {
        max = a[i][j];
        mIndexF = i;
        mIndexE = j;
      }
    }
  }
  for (k = 0; k < 4; k++) {
    for (l = 0; l < 4; l++) {
      if ((a[k][l] < max) && (status == 0)) {
        addition += a[k][l];
      } else {
        status++;
        if (a[k][l] != max) {
          multiplication *= a[k][l];
        }
      }
    }
  }
  printf("Addition is %dn", addition);
  printf("Multiplication is %d", multiplication);
  return 0;
}

我想找到最大值。还希望打印最大值之前的值的加法,并希望打印最大值之后的值的乘法。

可以这样做:

#define MAX_INT (((unsigned int)(-1))>>1)
#define MIN_INT (~(MAX_INT))
void minmax(int a[4][4])
{
    int i, j, maxi=0, maxj=0, max=MIN_INT, sum=0, mul=1;
    // this is for find out maximum value
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            if (max < a[i][j]) {
                max = a[i][j];
                maxi = i;
                maxj = j;
            }
        }
    }
    // this is to add and multiply
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            if (i< maxi || (i==maxi && j<maxj)) // this is "before" 
                 sum += a[i][j];
            else if (i==maxi && j==maxj)        // this is "same" 
                 ;                              //..nothing to do
            else mul *= a[i][j];
        }
    }
    printf("i,j=%d,%d; sum= %d, mul= %dn", maxi, maxj, sum, mul);
}

编辑:增加了MAX_INT和MIN_INT的定义

您的代码似乎是正确的:只需初始化

max=INT_MIN using include<limits.h>

你的第二个循环似乎有点不合适,你可以使用:

for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
    if(status==0)
        add+=disp[i][j];
    else if(status==1)
        mul*=disp[i][j];
    if(i==loc_i && j==loc_j)
        status=1;
}

然后减去

add-=disp[mIndexF][mIndexE];
    #include<stdio.h>
    void main(){
    int a[4][4]={
    {10,11,12,13},
    {14,15,16,17},
    {18,19,20,21},
    {22,2,3,3}
    };
    int max = a[0][0],mIndexF,mIndexE,addition = 0,multiplication =    1,i,j,status=0,k,l;
    // this is for find out maximum value
    for(i=0;i<4;i++){
    for(j=0;j<4;j++){
    if(max<a[i][j]){
    max = a[i][j];
    mIndexF=i;
    mIndexE=j;
    }
    }
    }
    printf("The maximum value is %dn", max);
    for(k=0;k<4;k++){
    for(l=0;l<4;l++){
    if((a[k][l]<max) &&(status==0)){
    addition+=a[k][l];
    }else{
    status++;
    if(a[k][l]!=max){
    multiplication*=a[k][l];
    }
    }
    }
    }
    printf("Addition is %dn",addition);
    printf("Multiplication is %d",multiplication);
    return 0;
    }

相关内容

  • 没有找到相关文章

最新更新