全主元高斯消元法 c语言实现
时间: 2023-11-25 13:08:46 浏览: 106
以下是C语言实现全主元高斯消元法的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 100
int main()
{
int n, i, j, k, p;
double a[N][N], b[N], x[N], m, s, t;
printf("请输入方程组的阶数n:");
scanf("%d", &n);
printf("请输入增广矩阵:\n");
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n + 1; j++)
{
scanf("%lf", &a[i][j]);
}
}
for (k = 1; k <= n - 1; k++)
{
m = 0;
for (i = k; i <= n; i++)
{
if (fabs(a[i][k]) > m)
{
m = fabs(a[i][k]);
p = i;
}
}
if (m == 0)
{
printf("系数矩阵奇异,无解!\n");
exit(1);
}
if (p != k)
{
for (j = k; j <= n + 1; j++)
{
t = a[k][j];
a[k][j] = a[p][j];
a[p][j] = t;
}
}
for (i = k + 1; i <= n; i++)
{
s = a[i][k] / a[k][k];
for (j = k + 1; j <= n + 1; j++)
{
a[i][j] = a[i][j] - s * a[k][j];
}
}
}
if (a[n][n] == 0)
{
printf("系数矩阵奇异,无解!\n");
exit(1);
}
x[n] = a[n][n + 1] / a[n][n];
for (i = n - 1; i >= 1; i--)
{
s = 0;
for (j = i + 1; j <= n; j++)
{
s = s + a[i][j] * x[j];
}
x[i] = (a[i][n + 1] - s) / a[i][i];
}
printf("方程组的解为:\n");
for (i = 1; i <= n; i++)
{
printf("x[%d]=%lf\n", i, x[i]);
}
return 0;
}
```
阅读全文