gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:38:49 27 4
gpt4 key购买 nike

这是我的代码

#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 %d\n", 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= %d\n", maxi, maxj, sum, mul);
}

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

关于c - 从二维数组中找到最大值,并将最大值之前的所有值相加,然后将最大值之后的所有值相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32340174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com