c++题目,下面是一个使用矩阵类CMatrix的程序实例及结果,请设计并完成矩阵类。
提示:可以用一维数组来实现
int main ()
{
int m = 3, n = 4;
CMatrix A (m, n);
int i, j;
for (i = 0; i < m ;i ++) {
for (j = 0; j < n; j ++)
A.ElementAt (i, j) = i * n+ j + 1;
}
A.Display ();
CMatrix B = A.Rotate ();//旋转
B.Display ();
return 0;
}
执行结果 :
1 2 3 4
5 6 7 8
9 10 11 12
1 5 9
2 6 10
3 7 11
4 8 12
实现截图:
#include <iostream>
using namespace std;
class CMatrix {
private:
int rows, cols;
double *elements;
public:
CMatrix(int r, int c) {
rows = r;
cols = c;
elements = new double[rows * cols];
for (int i = 0; i < rows * cols; i++) {
elements[i] = 0;
}
}
~CMatrix() {
delete[] elements;
}
double &ElementAt(int r, int c) {
return elements[r * cols + c];
}
CMatrix Rotate() {
CMatrix B(cols, rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
B.ElementAt(j, i) = ElementAt(i, j);
}
}
return B;
}
void Display() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << ElementAt(i, j) << " ";
}
cout << endl;
}
}