呵呵,最近好像冷落了我的BLOG。
今天练练手,实现了数值分析的GAUSS消元法。
具体代码:
#include<iostream>
#include <math.h>
using namespace std;
const int N = 2;
class gauss
{
private:
double a[N][N+1];
double x[N];
public:
gauss();
int find_max(int row_number);
void exchange_row(int larger_row_number, int smaller_row_number);
void re_set_row(int row_number);
bool caculate_out();
void print_out();
};
gauss::gauss()
{
int i,j;
for(i=1;i<N+1;i++)
{
cout<<"Please input row"<<i<<endl;
for(j=1;j<N+2;j++)
{
cout<<"Please input "<<"a["<<i<<"]["<<j<<"]";
cin>>a[i][j];
}
}
cout<<"gauss:gauss() inited ok"<<endl;
}
int gauss::find_max(int row_number)
{
int max_i=row_number;
int j;
for(int i=row_number+1;i<N+1;i++)
if(abs(a[j][row_number]) > abs(a[max_i][row_number]) )
max_i = j;
cout<<"gauss::find_max(int row_number) ok!"<<endl;
return max_i;
}
void gauss::exchange_row(int larger_row_number , int smaller_row_number)
{
// int max_one;
double max_value;
/*
if(larger_row_number < smaller_row_number )
{
max_one = larger_row_number;
larger_row_number = smaller_row_number;
smaller_row_number = max_one;
}
*/
for(int i=smaller_row_number;i<N+2;i++)
{
max_value = a[smaller_row_number][i];
a[smaller_row_number][i] = a[larger_row_number][i];
a[larger_row_number][i] = max_value;
}
cout<<"gauss::exchange_row(int larger_row_number, int smaller_row_number) ok!"<<endl;
}
void gauss::re_set_row(int row_number)
{
int i,j;
for(i=row_number+1;i<N+1;i++)
{
a[i][row_number]=a[i][row_number]/a[row_number][row_number];
for(j=row_number+1;j<N+2;j++)
a[i][j]=a[i][j]-a[i][row_number]*a[row_number][j];
}
cout<<"gauss::re_set_row(int row_number) ok !"<<endl;
}
bool gauss::caculate_out()
{
if(a[N][N] == 0)
{
cout<<"Sorry,there is no result!"<<endl;
return 0;
}
else
{
double sum;
x[N]=a[N][N+1]/a[N][N];
int j=0;
for(int k=N-1;k>0;k--)
{
sum=0;
for(j=k+1;j<N+1;j++)
{
sum+=a[k][j]*x[j];
}
x[k]=(a[k][N+1]-sum)/a[k][k];
}
}
cout<<"gauss::caculate_out() ok !"<<endl;
return 1;
}
void gauss::print_out()
{
for(int i=1;i<N+1;i++)
cout<<"x["<<i<<"] :"<<" "<<x[i]<<endl;
cout<<"gauss::print_out() ok!"<<endl;
}
int main()
{
gauss gau;
for(int counter=1;counter<N+1;counter++)
{
if(counter != gau.find_max(counter))
{
gau.exchange_row( gau.find_max(counter) , counter );
}
gau.re_set_row(counter);
}
if( gau.caculate_out())
{
gau.print_out();
cout<<"ok,I have finished gauss ";
}
else { cout<<"Sorry ,there is no result!"; }
return 1;
}