gpt4 book ai didi

c++ - 在二维数组中查找最小值和最大值?

转载 作者:行者123 更新时间:2023-11-28 04:30:48 24 4
gpt4 key购买 nike

运行此代码后,它将生成所需行和列的随机数组。然后循环将数组按其对角线分为上侧和下侧。在上侧,循环将查找 max number,在下侧,循环将查找 最小数量 .然后在最后阶段我需要改变 minmax 的位置。 Max 代替 min,反之亦然。代码运行并找到 minmax。不要知道如何改变他们的位置。

Code

#include <iostream>
#include <time.h>
#include <limits.h>


using namespace std;

int main(){
int rows, columns;
int max = INT_MAX;
int min = INT_MIN;
int XindexOfMax, YindexOfMax;
int XindexOfMin, YindexOfMin;

cout << "Enter rows: ";
cin >> rows;
cout << "Enter columns: ";
cin >> columns;

int **array = new int *[rows]; //generating random array
for(int i = 0; i < rows; i++)
array[i] = new int[columns];

srand((unsigned int)time(NULL)); //generating randoms

for(int i = 0; i < rows; i++){ //loop for the main array
for(int j = 0; j < columns; j++){
array[i][j] = rand() % 10;
cout << array[i][j] << " ";
}
cout << "\n";
}

cout << "For finding Max: " << endl;

for(int i = 0; i < rows; i++){ //upper half of the diagonal
for(int j = 0; j < columns - i; j++){
cout << array[i][j] << " ";
if(array[i][j] > max){
max = array[i][j];
XindexOfMax = i; //find x and y coordinates if max
YindexOfMax = j;
}

}
cout << "\n";
}
cout << "For finding Min: " << endl;

for (int i = 0; i < rows; i++){ // lower half of the diagonal
for (int j = 0; j < columns; j++){
if (j < columns - i - 1){
cout << " ";
}
else{
cout << array[i][j] << " ";
if(array[i][j] < min){
min = array[i][j];
XindexOfMin = i; //find x and y coordinates if min
YindexOfMin = j;
}
}
}
cout << "\n";
}
cout << "Result" << endl;
//swapping positions of min and max
std::swap(array[XindexOfMax][YindexOfMax], array[XindexOfMin][YindexOfMin]);

for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
cout << array[i][j] << " "; //Printing the final array
}
cout << "\n";
}
return 0;
}

最佳答案

除了minmax值,您需要记住找到 min 的索引和 max , 分别。然后您可以交换值(手动或使用 std::swap )。

顺便说一句:你需要初始化maxminINT_MININT_MAX ,而不是相反。所以必须是

int max = INT_MIN;
int min = INT_MAX;

否则,如果你写int max = INT_MAX , 那么就没有像 if(array[i][j] > max) 这样的比较了将永远评估为真,因为没有大于 INT_MAX 的整数值.

关于c++ - 在二维数组中查找最小值和最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014607/

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