用C++实现固定维度矩阵的基本运算,矩阵维度为6×6,要求不使用第三方库,将数组指针作为函数参数。
时间: 2024-03-11 11:49:24 浏览: 58
c++关于矩阵的运算
4星 · 用户满意度95%
以下是用C++实现固定维度矩阵基本运算的示例代码:
```c++
#include <iostream>
using namespace std;
const int ROW = 6;
const int COL = 6;
// 矩阵加法
void matrix_addition(int a[][COL], int b[][COL], int c[][COL])
{
for(int i = 0; i < ROW; i++)
{
for(int j = 0; j < COL; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
// 矩阵减法
void matrix_subtraction(int a[][COL], int b[][COL], int c[][COL])
{
for(int i = 0; i < ROW; i++)
{
for(int j = 0; j < COL; j++)
{
c[i][j] = a[i][j] - b[i][j];
}
}
}
// 矩阵乘法
void matrix_multiplication(int a[][COL], int b[][COL], int c[][COL])
{
for(int i = 0; i < ROW; i++)
{
for(int j = 0; j < COL; j++)
{
c[i][j] = 0;
for(int k = 0; k < ROW; k++)
{
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
// 矩阵转置
void matrix_transpose(int a[][COL], int b[][ROW])
{
for(int i = 0; i < ROW; i++)
{
for(int j = 0; j < COL; j++)
{
b[j][i] = a[i][j];
}
}
}
// 输出矩阵
void print_matrix(int a[][COL])
{
for(int i = 0; i < ROW; i++)
{
for(int j = 0; j < COL; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}
int main()
{
int a[ROW][COL] = {{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}};
int b[ROW][COL] = {{6, 5, 4, 3, 2, 1},
{12, 11, 10, 9, 8, 7},
{18, 17, 16, 15, 14, 13},
{24, 23, 22, 21, 20, 19},
{30, 29, 28, 27, 26, 25},
{36, 35, 34, 33, 32, 31}};
int c[ROW][COL] = {};
int d[COL][ROW] = {};
// 矩阵加法
matrix_addition(a, b, c);
cout << "a + b = " << endl;
print_matrix(c);
// 矩阵减法
matrix_subtraction(a, b, c);
cout << "a - b = " << endl;
print_matrix(c);
// 矩阵乘法
matrix_multiplication(a, b, c);
cout << "a * b = " << endl;
print_matrix(c);
// 矩阵转置
matrix_transpose(a, d);
cout << "a的转置 = " << endl;
print_matrix(d);
return 0;
}
```
在上述代码中,首先定义了矩阵的行列数,然后实现了矩阵加法、矩阵减法、矩阵乘法、矩阵转置等基本运算的函数。最后在主函数中定义了两个6×6的矩阵a和b,以及一个6×6的结果矩阵c以及一个6×6的转置矩阵d。分别调用矩阵加法、矩阵减法、矩阵乘法、矩阵转置函数,并输出结果矩阵。
阅读全文