列主元高斯消去法c++完整版
时间: 2024-01-04 18:20:03 浏览: 67
以下是列主元高斯消去法的C++完整版代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
const double EPSILON = 1e-10; // 定义一个极小值,用于判断浮点数是否为0
void gaussianElimination(double **A, double *B, int n) {
// 高斯消去
for (int k = 0; k < n - 1; k++) {
// 选取主元
int maxRow = k;
double maxVal = fabs(A[k][k]);
for (int i = k + 1; i < n; i++) {
if (fabs(A[i][k]) > maxVal) {
maxRow = i;
maxVal = fabs(A[i][k]);
}
}
// 交换行
if (maxRow != k) {
for (int j = k; j < n; j++) {
swap(A[k][j], A[maxRow][j]);
}
swap(B[k], B[maxRow]);
}
// 消元
for (int i = k + 1; i < n; i++) {
double factor = A[i][k] / A[k][k];
for (int j = k; j < n; j++) {
A[i][j] -= factor * A[k][j];
}
B[i] -= factor * B[k];
}
}
// 回代求解
double *X = new double[n];
for (int i = n - 1; i >= 0; i--) {
X[i] = B[i];
for (int j = i + 1; j < n; j++) {
X[i] -= A[i][j] * X[j];
}
X[i] /= A[i][i];
}
// 输出结果
cout << "The solution is: ";
for (int i = 0; i < n; i++) {
cout << X[i] << " ";
}
cout << endl;
delete[] X;
}
int main() {
int n;
cout << "Enter the number of equations: ";
cin >> n;
double **A = new double*[n];
double *B = new double[n];
cout << "Enter the coefficients of the equations:" << endl;
for (int i = 0; i < n; i++) {
A[i] = new double[n];
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
cout << "Enter the constants of the equations:" << endl;
for (int i = 0; i < n; i++) {
cin >> B[i];
}
gaussianElimination(A, B, n);
for (int i = 0; i < n; i++) {
delete[] A[i];
}
delete[] A;
delete[] B;
return 0;
}
```
阅读全文