C++中实现矩阵的加法和乘法实例
实现效果图:
实例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
#include<iostream>
using namespace std;
class Matrix
{
int row; //矩阵的行
int col; //矩阵的列
int **a; //保存二维数组的元素
public :
Matrix(); //默认构造函数
Matrix( int r, int c);
Matrix( const Matrix &is); //拷贝构造函数
void Madd( const Matrix &is); //矩阵加
Matrix Mmul( const Matrix &is); //矩阵乘
void display(); //显示矩阵元素
};
Matrix::Matrix( int r, int c)
{
row = r;
col = c;
a = ( int **) malloc ( sizeof ( int *)*row);
for ( int r = 0; r < row; r++)
{
*(a + r) = ( int *) malloc ( sizeof ( int )*col);
}
printf ( "请输入数:\n" );
for ( int i = 0; i < row; i++)
for ( int j = 0; j < col; j++)
cin >> a[i][j];
}
Matrix::Matrix( const Matrix & is)
{ //拷贝构造函数
row = is.row;
col = is.col;
a = new int *[row];
for ( int i = 0; i < row; i++)
{
a[i] = new int [col];
}
a = is.a;
}
void Matrix::Madd( const Matrix & is)
{
if (row != is.row || col != is.col) //判断两矩阵是否符合相加条件
{
cout << "相加的矩阵必须行和列一致" ;
}
else
{
for ( int i = 0; i < row; i++)
{
for ( int j = 0; j < col; j++)
{
a[i][j] += is.a[i][j];
}
}
}
}
Matrix Matrix::Mmul( const Matrix & is)
{
Matrix M3( this ->row, is.col);
if ( this ->col != is.row) //判断是否符合相乘条件
{
cout << "不符合两矩阵相乘的条件" ;
}
else
{
for ( int i = 0; i < M3.row; i++)
{
for ( int j = 0; j < M3.col; j++)
{
M3.a[i][j] = 0;
for ( int n = 0; n < is.row; n++)
{
M3.a[i][j] += this ->a[i][n] * is.a[n][j];
}
}
}
}
return M3;
}
void Matrix::display()
{ //输出矩阵
for ( int i = 0; i < row; i++)
{
for ( int j = 0; j < col; j++)
{
cout << a[i][j] << " " ;
}
cout << endl;
}
cout << endl;
}
int main()
{
Matrix m1(3, 3);
m1.display();
Matrix m2(3, 3);
m2.display();
Matrix m3(3, 2);
m3.display();
cout << "m1+m2=" << endl;
m1.Madd(m2);
m1.display();
Matrix m4(m1.Mmul(m3));
cout << "m1*m3=" << endl;
m4.display();
system ( "pause" );
return 0;
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://www.cnblogs.com/Alier/p/6651444.html