用C++编写线性方程组求解
以下是基于高斯-约旦消元法的C++代码实现线性方程组求解:
#include <iostream>
#include <cmath>
using namespace std;
const int MAX_SIZE = 50; // 最大方程组大小
const double EPSILON = 1e-10; // 零的阈值
void swap(double& a, double& b) // 交换两个数
{
double temp = a;
a = b;
b = temp;
}
void printEquation(double matrix[MAX_SIZE][MAX_SIZE + 1], int n) // 打印方程组
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= n; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
}
int solveEquation(double matrix[MAX_SIZE][MAX_SIZE + 1], int n) // 解方程组
{
for (int i = 0; i < n; i++) // 按列进行消元
{
int pivot = i; // 选主元
for (int j = i + 1; j < n; j++)
{
if (fabs(matrix[j][i]) > fabs(matrix[pivot][i]))
pivot = j;
}
if (fabs(matrix[pivot][i]) < EPSILON) // 主元为零,方程组无解
return 0;
if (pivot != i) // 交换两行
{
for (int j = i; j <= n; j++)
swap(matrix[i][j], matrix[pivot][j]);
}
for (int j = i + 1; j < n; j++) // 消元
{
double ratio = matrix[j][i] / matrix[i][i];
for (int k = i; k <= n; k++)
matrix[j][k] -= ratio * matrix[i][k];
}
}
for (int i = n - 1; i >= 0; i--) // 回代求解
{
for (int j = i + 1; j < n; j++)
matrix[i][n] -= matrix[i][j] * matrix[j][n];
if (fabs(matrix[i][i]) < EPSILON) // 主元为零,方程组无解
return 0;
matrix[i][n] /= matrix[i][i];
}
return 1;
}
int main()
{
double matrix[MAX_SIZE][MAX_SIZE + 1]; // 增广矩阵
int n; // 方程组大小
cout << "请输入方程组大小n:";
cin >> n;
cout << "请输入增广矩阵:" << endl;
for (int i = 0; i < n; i++)
for (int j = 0; j <= n; j++)
cin >> matrix[i][j];
if (solveEquation(matrix, n)) // 方程组有解
{
cout << "方程组的解为:" << endl;
for (int i = 0; i < n; i++)
cout << "x[" << i + 1 << "] = " << matrix[i][n] << endl;
}
else // 方程组无解
cout << "方程组无解!" << endl;
return 0;
}
下面是一个使用样例:
请输入方程组大小n:3
请输入增广矩阵:
1 2 -1 2
3 2 2 3
-1 3 -1 1
方程组的解为:
x[1] = 1
x[2] = -1
x[3] = 2
注:此代码仅适用于系数矩阵是非奇异矩阵的情况,如果系数矩阵是奇异矩阵,则需要使用其他方法求解。
原文地址: https://www.cveoy.top/t/topic/pWr 著作权归作者所有。请勿转载和采集!