我在C++中使用Gauss-Jordan消元來求解線性方程組。 代碼正常工作。想知道爲什麼行1,2,3中的行1,2,338不能被第4行替換(這樣做後得到不正確的輸出)?C++中的Gauss-Jordan消除方法
#include <iostream>
using namespace std;
class Gauss
{
float a[50][50];
int n;
public:
void accept()
{
cout<<"Enter no. of variables: ";
cin>>n;
for(int i=0;i<n;i++)
{
for(int j=0;j<n+1;j++)
{
if(j==n)
cout<<"Constant no."<<i+1<<" = ";
else
cout<<"a["<<i+1<<"]["<<j+1<<"] = ";
cin>>a[i][j];
}
}
}
void display()
{
for(int i=0;i<n;i++)
{
cout<<"\n";
for(int j=0;j<n+1;j++)
{
if(j==n)
cout<<" ";
cout<<a[i][j]<<"\t";
}
}
}
void gauss()//converting augmented matrix to row echelon form
{
float temp;//Line 1
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
temp=a[j][i]/a[i][i];//Line 2
for(int k=i;k<n+1;k++)
{
a[j][k]-=temp*a[i][k];//Line 3
//a[j][k]-=a[j][i]*a[i][k]/a[i][i];//Line 4
}
}
}
}
void EnterJordan()//converting to reduced row echelon form
{
float temp;
for(int i=n-1;i>=0;i--)
{
for(int j=i-1;j>=0;j--)
{
temp=a[j][i]/a[i][i];
for(int k=n;k>=i;k--)
{
a[j][k]-=temp*a[i][k];
}
}
}
float x[n];
for(int i=0;i<n;i++)//making leading coefficients zero
x[i]=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n+1;j++)
{
if(x[i]==0&&j!=n)
x[i]=a[i][j];
if(x[i]!=0)
a[i][j]/=x[i];
}
}
}
void credits()
{
for(int i=0;i<n;i++)
{
cout<<"\nx"<<i+1<<" = "<<a[i][n]<<endl;
}
}
};
int main()
{
Gauss obj;
obj.accept();
cout<<"\n\nAugmented matrix: \n\n\n";
obj.display();
obj.gauss();
cout<<"\n\nRow Echelon form: \n\n\n";
obj.display();
obj.EnterJordan();
cout<<"\n\nReduced row echelon form:\n\n\n";
obj.display();
cout<<"\n\nSolution: \n\n\n";
obj.credits();
return 0;
}
注:當樞軸爲零我的代碼不考慮劃分的問題(我選擇對角線元素每次轉動)。 對於我試過的特定例子,沒有遇到這種情況。
增廣矩陣是:
2 1 -1 8
-3 -1 2 -11
-2 1 2 -3
輸出矩陣爲:
1 0 0 2
0 1 0 3
0 0 1 -1
和解決辦法是:
x1 = 2
x2 = 3
x3 = -1
使用第4行中,輸出矩陣爲:
1 0 0 -0.75
0 1 -0 8
0 0 1 -1.5
和解決辦法是:
x1 = -0.75
x2 = 8
x3 = -1.5
「a」的聲明在哪裏?有這些代碼的任何工作是相當重要的。 –
抱歉!忘了提及它。這是一個浮點數組,我在類中聲明爲float a [50] [50]; – ByteMan2021
如果您包含所有相關代碼以便可以複製問題,您將獲得更好更快的響應。 –