#include<iostream>
using namespace std;
template<typename T>
T** Allocation2D(int m, int n)
{
T** a;
a = new T* [m];
for (int i = 0;i < m;i++)
{
a[i] = new T[n];
}
return a;
}
template<typename T>
T* Allocation1D(int n)
{
T* a;
a = new T[n];
return a;
}
int main()
{
int i, j, k;
int n;
float** a;
cout << "输入系数矩阵的N值:" << endl;
cin >> n;
a = Allocation2D<float>(n, n + 1);
cout << endl << "输入增广矩阵的各值:" << endl;
for (i = 0;i < n;i++)
{
for (j = 0;j < n + 1;j++)
{
cin >> a[i][j];
}
}
int* e;
e = Allocation1D<int>(n);
for (i = 0;i < n;i++)
{
e[i] = i;
}
float temp;
int row, col;
for (k = 0;k < n - 1;k++)
{
temp = 0;
row = 0;
col = 0;
for(i=k;i<n;i++)
{
for (j = k;j < n;j++)
{
if (fabs(a[i][j]) > temp)
{
temp = a[i][j];
row = i;
col = j;
}
}
}
if (temp == 0)
{
cout << "系数矩阵为奇异矩阵" << endl;
return 0;
}
if (row != k)
{
for (j = k;j < n + 1;j++)
{
temp = a[k][j];
a[k][j] = a[row][j];
a[row][j] = temp;
}
}
if (col != k)
{
e[k] = col;
for (i = k;i < n;i++)
{
temp = a[i][k];
a[i][k] = a[i][col];
a[i][col] = temp;
}
}
for (i = k + 1;i < n;i++)
{
float L = -(a[i][k] / a[k][k]);
a[i][k] = 0;
for (j = k + 1;j < n;j++)
{
a[i][j] = L * a[k][k] + a[i][j];
}
a[i][n - 1] = L * a[k][n - 1] + a[i][n - 1];
}
}
float* x;
x = Allocation1D<float>(n);
x[n - 1] = a[n - 1][n] / a[n - 1][n - 1];
for (k = n - 2;k >= 0;k--)
{
temp = 0;
for (j = k + 1;j < n;j++)
{
temp = temp + a[k][j] * a[j][n];
}
x[k] = (a[k][n] - temp) / a[k][k];
}
for (k = n - 2;k >= 0;k--)
{
if (e[k] != k)
{
temp = x[e[k]];
x[e[k]] = x[k];
x[k] = temp;
}
}
cout << "解向量为:" << endl;
for (i = 0;i < n;i++)
{
cout << "x" << i + 1 << ":" << x[i] << endl;
}
return 0;
}
|