C++中实现矩阵的加法和乘法实例
2026/4/27 5:28:22 网站建设 项目流程

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>

usingnamespacestd;

classMatrix

{

introw;//矩阵的行

intcol;//矩阵的列

int**a;//保存二维数组的元素

public:

Matrix();//默认构造函数

Matrix(intr,intc);

Matrix(constMatrix &is);//拷贝构造函数

voidMadd(constMatrix &is);//矩阵加

Matrix Mmul(constMatrix &is);//矩阵乘

voiddisplay();//显示矩阵元素

};

Matrix::Matrix(intr,intc)

{

row = r;

col = c;

a = (int**)malloc(sizeof(int*)*row);

for(intr = 0; r < row; r++)

{

*(a + r) = (int*)malloc(sizeof(int)*col);

}

printf("请输入数:\n");

for(inti = 0; i < row; i++)

for(intj = 0; j < col; j++)

cin >> a[i][j];

}

Matrix::Matrix(constMatrix & is)

{//拷贝构造函数

row = is.row;

col = is.col;

a =newint*[row];

for(inti = 0; i < row; i++)

{

a[i] =newint[col];

}

a = is.a;

}

voidMatrix::Madd(constMatrix & is)

{

if(row != is.row || col != is.col)//判断两矩阵是否符合相加条件

{

cout <<"相加的矩阵必须行和列一致";

}

else

{

for(inti = 0; i < row; i++)

{

for(intj = 0; j < col; j++)

{

a[i][j] += is.a[i][j];

}

}

}

}

Matrix Matrix::Mmul(constMatrix & is)

{

Matrix M3(this->row, is.col);

if(this->col != is.row)//判断是否符合相乘条件

{

cout <<"不符合两矩阵相乘的条件";

}

else

{

for(inti = 0; i < M3.row; i++)

{

for(intj = 0; j < M3.col; j++)

{

M3.a[i][j] = 0;

for(intn = 0; n < is.row; n++)

{

M3.a[i][j] +=this->a[i][n] * is.a[n][j];

}

}

}

}

returnM3;

}

voidMatrix::display()

{//输出矩阵

for(inti = 0; i < row; i++)

{

for(intj = 0; j < col; j++)

{

cout << a[i][j] <<" ";

}

cout << endl;

}

cout << endl;

}

intmain()

{

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");

return0;

}

感谢阅读,希望能帮助到大家

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询