顺序高斯消元
#include <stdio.h>
#include <string.h>
double a[101][101];
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
#endif
int i, j, k, n, flag = 0, maxi = 0, maxv = 0;
double u, v, ans = 0, x[101] = {0}, b[101], l;
scanf("%d", &n);
for (i = 1; i < n + 1; i++)
{
x[i] = 0x3f3f3f;
for (j = 1; j < n + 1; j++)
{
scanf("%lf", &a[i][j]);
}
scanf("%lf", &b[i]);
}
for (i = 1; i < n; i++)
{
maxi = a[i][i];
maxv = i;
for (j = i + 1; j < n + 1; j++)
{
if (maxi < a[j][i])
{
maxi = a[j][i];
maxv = j;
}
}
if (a[maxv][i] == 0)
{
flag = 1;
break;
}
if (maxv != i)
{
double tmp;
for (j = 1; j < n + 1; j++)
{
tmp = a[i][j];
a[i][j] = a[maxv][j];
a[maxv][j] = tmp;
}
tmp = b[maxv];
b[maxv] = b[i];
b[i] = tmp;
}
for (j = i + 1; j <= n; j++)
{
u = a[j][i] / a[i][i];
for (k = i; k < n + 1; k++)
{
l = a[i][k] * u;
a[j][k] -= l;
}
l = u * b[i];
b[j] -= l;
}
}
v = 0;
for (i = n; i >= 1; i--)
{
for (j = i + 1; j < n + 1; j++)
{
if (x[j] == 0x3f3f3f)
{
flag = 1;
break;
}
l = a[i][j] * x[j];
v += l;
}
b[i] -= v;
if (a[i][i] == 0)
{
flag = 1;
break;
}
x[i] = b[i] / a[i][i];
v = 0;
}
if (flag == 1)
{
printf("No Solution\n");
}
else
{
for (i = 1; i < n + 1; i++)
{
printf("%.2f\n", x[i]);
}
}
return 0;
}
选列主元高斯消元:
#include <stdio.h>
#include <string.h>
double a[101][101];
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
#endif
int i, j, k, n, flag = 0, maxi = 0, maxv = 0;
double u, v, ans = 0, x[101] = {0}, b[101], l;
scanf("%d", &n);
for (i = 1; i < n + 1; i++)
{
x[i] = 0x3f3f3f;
for (j = 1; j < n + 1; j++)
{
scanf("%lf", &a[i][j]);
}
scanf("%lf", &b[i]);
}
for (i = 1; i < n; i++)
{
maxi = a[i][i];
maxv = i;
for (j = i + 1; j < n + 1; j++)
{
if (maxi < a[j][i])
{
maxi = a[j][i];
maxv = j;
}
}
if (a[maxv][i] == 0)
{
flag = 1;
break;
}
if (maxv != i)
{
double tmp;
for (j = 1; j < n + 1; j++)
{
tmp = a[i][j];
a[i][j] = a[maxv][j];
a[maxv][j] = tmp;
}
tmp = b[maxv];
b[maxv] = b[i];
b[i] = tmp;
}
for (j = i + 1; j <= n; j++)
{
u = a[j][i] / a[i][i];
for (k = i; k < n + 1; k++)
{
l = a[i][k] * u;
a[j][k] -= l;
}
l = u * b[i];
b[j] -= l;
}
}
v = 0;
for (i = n; i >= 1; i--)
{
for (j = i + 1; j < n + 1; j++)
{
if (x[j] == 0x3f3f3f)
{
flag = 1;
break;
}
l = a[i][j] * x[j];
v += l;
}
b[i] -= v;
if (a[i][i] == 0)
{
flag = 1;
break;
}
x[i] = b[i] / a[i][i];
v = 0;
}
if (flag == 1)
{
printf("No Solution\n");
}
else
{
for (i = 1; i < n + 1; i++)
{
printf("%.2f\n", x[i]);
}
}
return 0;
}