#include<iostream>
#include<vector>
#include<math.h>
using namespace std;
void print_func(float(*arr)[15], int n);
void exchange_func(float(*arr)[15], int n);
void sol_func(float(*arr)[15], int n);
int main()
{
size_t n;
float a[15][15];
cout << "Please input the matrix Row: " << endl;
cin >> n;
for (auto i = 1; i <= n; i++) //输入系数矩阵
{
cout << "Please input the " << i << " row value" << endl;
for (auto j = 1; j <= n; j++)
cin >> a[i][j];
}
cout << "请输入未知量:" << endl;
for (auto i = 1; i <= n; i++)
{
cin >> a[i][n+1];
}
cout << "方程的增广矩阵是:" << endl;
print_func(a, n); //调用打印函数
exchange_func(a, n);
return 0;
}
void exchange_func(float(*arr)[15], int n) //定义一个列主元消除的函数
{
for (auto k = 1; k <= n-1; k++)
{
int row = 0;
float max = 0;
for (auto i = k; i <= n; i++) //找到最大值所在的行,找到行数
{
if (fabs(arr[i][k] > max))
{
max = fabs(arr[i][k]);
row = i;
}
}
if (arr[row][k] == 0)
{
cout << "CANT'T CALCULAR!" << endl;
return;
}
for (auto j = 1;j <= n + 1; j++) //行交换
{
float temp = 0;
temp = arr[row][j];
arr[row][j] = arr[k][j];
arr[k][j] = temp;
}
cout << "选列主元:" << endl;
print_func(arr, n);
for (auto i = k + 1; i <= n ; i++)
{
float d = arr[i][k] / arr[k][k];
for (auto j = 1; j <= n + 1; j++)
{
arr[i][j] = arr[i][j] - d * arr[k][j]; //每一行元素行变换
}
}
cout << "消元:" << endl;
print_func(arr, n);
}
sol_func(arr, n);
}
void sol_func(float(*arr)[15], int n) //求解函数
{
float x[15] = {};
for (auto i = n; i >= 1;i--)
{
float sum = 0;
for (auto k = 1; k <= n; k++)
{
if(k!=i)
sum += x[k] * arr[i][k]; //每一行的系数乘以对应的x[i]
}
x[i] = (arr[i][n + 1] - sum) / arr[i][i]; //求解x[i]
}
cout << "x solution is: " << endl;
for (auto i = 1; i <= n;i++)
{
cout << x[i] << " ";
}
cout << '\n';
}
void print_func(float(*arr)[15], int n) //定义一个打印函数
{
for (auto i = 1;i <= n; i++)
{
for (auto j = 1; j <= n + 1;j++)
cout << arr[i][j] << "\t";
cout << '\n';
}
cout << "----------------------" << endl;
}
The result of the operation is as follows
The input coefficient matrix is R, and the unknown matrix is V
The last line of the program running result is the value of X1~X9