C++ 生成随机数矩阵并交换数字位置
以下是生成随机数矩阵并交换数字位置的 C++ 代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int ROWS = 8;
const int COLS = 8;
void printMatrix(int matrix[][COLS], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << ' '; // 使用单引号
}
cout << endl;
}
}
void swapNumbers(int matrix[][COLS], int rows, int cols) {
int x1, y1, x2, y2;
cout << "Enter the coordinates of the first number (row column): ";
cin >> x1 >> y1;
cout << "Enter the coordinates of the second number (row column): ";
cin >> x2 >> y2;
if (x1 < 0 || x1 >= rows || x2 < 0 || x2 >= rows || y1 < 0 || y1 >= cols || y2 < 0 || y2 >= cols) {
cout << "Invalid coordinates. Please try again." << endl;
return;
}
int temp = matrix[x1][y1];
matrix[x1][y1] = matrix[x2][y2];
matrix[x2][y2] = temp;
}
int main() {
int matrix[ROWS][COLS];
srand(time(0)); // Seed the random number generator with the current time
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
matrix[i][j] = rand() % 10; // Generate random numbers between 0 and 9
}
}
cout << "Randomly generated matrix:" << endl;
printMatrix(matrix, ROWS, COLS);
swapNumbers(matrix, ROWS, COLS);
cout << "Matrix after swapping two numbers:" << endl;
printMatrix(matrix, ROWS, COLS);
return 0;
}
这个程序首先生成一个 8x8 的随机数矩阵,然后让用户输入两个数字的坐标,然后交换它们的位置,并输出交换后的矩阵。请注意,此程序只能交换矩阵中的两个数字,而不能交换两行或两列。如果用户输入的坐标无效,程序将提示用户重新输入。
原文地址: http://www.cveoy.top/t/topic/oTd1 著作权归作者所有。请勿转载和采集!