程序代码:
#include <iostream> #include <fstream> #include <cstdlib> #include <ctime> using namespace std; class RandomMatrix { int rows; int cols; int matrix[20][20]; ofstream MatrixA; ofstream OutputMatrix; public: RandomMatrix(int r, int c) : rows(r), cols(c), MatrixA("MatrixA.txt"), OutputMatrix("OutputMatrix.txt") { random(); } bool isPrime(int) const; void random(); void output1(); void output2(); }; bool RandomMatrix::isPrime(int num) const { if (num % 2 == 0) return false; for (int i = 2; i < num; i++) if (num % i == 0) return false; return true; } void RandomMatrix::random() { srand(time(0)); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = rand() % 100; } void RandomMatrix::output1() { MatrixA << rows << endl; MatrixA << cols << endl; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) MatrixA << matrix[i][j] << " "; MatrixA << endl; } } void RandomMatrix::output2() { OutputMatrix << rows << endl; OutputMatrix << rows << endl; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) if (isPrime(matrix[i][j])) OutputMatrix << 0 << " "; else OutputMatrix << matrix[i][j] << " "; OutputMatrix << endl; } } int main() { int r = 0, c = 0; cout << "Enter rows and columns between 10 to 20:" << endl; failed: cin >> r >> c; if (r < 10 || r > 20 || c < 10 || c > 20) { cout << "Error, rows and columns must between 10 to 20." << endl; cout << "Try again!" << endl; goto failed; } RandomMatrix rm(r, c); rm.output1(); rm.output2(); }
My life is brilliant