肺炎期间上网课,学习工程与科学计算的一个作业
代码通过c++进行实现
借鉴了大佬的算法思想,原帖地址https://blog.youkuaiyun.com/qq_26025363/article/details/53044843
解决了几个问题,一个是原来代码输入偶数数组结果有误,另外是输出的数组第一列不为零。如有问题或建议欢迎指正
#include <iostream>
#include <cmath>
using namespace std;
const int n = 4;
//交换2个数的大小函数模板
template <class T>
void Inverse(T *a, T *b)
{
T c;
c = *a;
*a = *b;
*b = c;
}
//高斯列主元素消元法
void gaussLine(double a[n][n], double b[n])
{
int i, j, k;
int row, col;
for (k = 0; k < n - 1; k++) //k是列 i是行
{
double maxnum = 0;
//找出消元列中最大的那个元素所在的位置
for (i = k; i < n; i++)
if (fabs(a[i][k]) > maxnum)
{
maxnum = fabs(a[i][k]);
// cout << "maxnum " << maxnum << endl;
row = i;
col = k;
}
//如果该对角线元素是0,同样不能用高斯消元法来求解
if (a[row][row] == 0)
{
cout << "GaussLine can't solve" << endl;
return;
}
//将找出的行进行交换
if (k != row)
for (i = 0; i < n; i++)
{
Inverse(a[row] + i, a[k] + i);
}
Inverse((b + k), (b + row));
//消元过程
double c[n];
for (j = k + 1; j < n; j++)
{
c[j] = a[j][k] / a[k][k];
}
for (i = k + 1; i < n; i++)
{
for (j = 0; j < n; j++)
{
a[i][j] = a[i][j] - c[i] * a[k][j];
}
b[i] = b[i] - c[i] * b[k];
}
}
double x[n];
x[n - 1] = b[n - 1] / a[n - 1][n - 1];
for (i = n - 2; i >= 0; i--)
{
double sum = 0;
for (j = i + 1; j < n; j++)
sum += a[i][j] * x[j];
x[i] = (b[i] - sum) / a[i][i];
}
//打印输出
for (i = 0; i < n; i++)
cout << " x "
<< "[" << i << "]=" << x[i] << endl;
int i1, j1;
for (i1 = 0; i1 < n; i1++)
{
for (j1 = 0; j1 < n; j1++)
cout << a[i1][j1] << '\t';
cout << endl;
}
}
int main()
{
double a[4][4] = {1.1348, 3.8326, 1.1651, 3.4017,
0.59301, 1.7875, 2.5330, 1.5435,
3.4129, 4.9317, 8.7643, 1.3142,
1.2371, 4.9998, 10.6721, 0.0147};
int i, j;
double b[4] = {9.5342, 6.3941, 18.4231, 16.9237};
gaussLine(a, b);
cin.get();
return 0;
}
上网课really不舒服,想念学校呜呜呜~