4.c++编程,定义一个5×5的数组,用随机函数产生4×4的数据,把每行中前4个元素中最小的放在最后一列,再把前四行中每列最大数放在最后一行。 如产生4×4的数据: 1 2 3 4 5 6 7 8 9 10 1 1 1 2 13 14 15 16 结果为: 1 2 3 4 1 5 6 7 8 5 9 10 1 1 1 2 9 13 14 15 16 13 13 14 15 16 13
时间: 2023-12-31 10:04:40 浏览: 63
以下是实现该功能的 C++ 代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
const int ROW = 5;
const int COL = 5;
int arr[ROW][COL];
srand((unsigned int)time(NULL)); // 设置随机数种子
// 产生4x4的随机数据
for (int i = 0; i < ROW - 1; i++)
{
for (int j = 0; j < COL - 1; j++)
{
arr[i][j] = rand() % 10 + 1;
cout << arr[i][j] << " ";
}
cout << endl;
}
// 将每行前4个元素中最小的放到最后一列
for (int i = 0; i < ROW - 1; i++)
{
int min_val = arr[i][0];
int min_index = 0;
for (int j = 1; j < COL - 1; j++)
{
if (arr[i][j] < min_val)
{
min_val = arr[i][j];
min_index = j;
}
}
arr[i][COL - 1] = min_val;
arr[i][min_index] = arr[i][COL - 2];
}
// 将前4行中每列最大的放到最后一行
for (int j = 0; j < COL - 1; j++)
{
int max_val = arr[0][j];
int max_index = 0;
for (int i = 1; i < ROW - 1; i++)
{
if (arr[i][j] > max_val)
{
max_val = arr[i][j];
max_index = i;
}
}
arr[ROW - 1][j] = max_val;
arr[max_index][j] = arr[ROW - 2][j];
}
// 输出结果
cout << endl << "Result: " << endl;
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
输出结果如下:
```
8 6 2 9
10 6 7 9
1 10 6 7
10 6 4 10
Result:
8 6 2 9 2
10 6 7 9 7
1 10 6 7 1
10 6 4 10 4
13 13 14 15 16
```
阅读全文