本文介绍了我尝试使用类概念为3 * 3矩阵编写高斯消除程序。但是这段代码每次显示0 0 0结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
#include<string>
#include<cmath>
#include<vector>


using namespace std;


class matrix{

private:
int row;
int coloumn;
double * x;

public:
matrix();
matrix(int nrow,int ncol);
double * gaussElimination(double **a , double *b,matrix & u);
~matrix();


};

matrix::matrix()
{
    row=0 ;
    coloumn=0;
    x=NULL;
}

matrix::~matrix()
{delete x;}

matrix::matrix(int nrow,int ncol)
{
    row=nrow;
    coloumn= ncol;
    for (int i=0;i<row;i++)
        {x=new double [row+1];}
}

double * matrix:: gaussElimination (double ** a,double *b,matrix & u)
{
    int m,n,i,j,k;
    m=u.row;
    n=u.coloumn;
    
    a=new double * [m+1];
    b=new double  [m+1];
    
    for (i=1;i<n;i++)
    {
         a[i]=new double [n+1];
    }

    // row operations
    double Sum,ratio;
    for (k=1;k<=m-1;k++)
        for (i=k+1;i<=m;i++)
        {
            ratio=a[i][k]/a[k][k];
            for (j=1;j<=m;j++)
                a[i][j] -= ratio*a[k][j];
            b[i] -= ratio*b[k];
        }
    
    // backward substitutions
    for (i=m;i>=1;i--)
    {
        Sum=0;
        x[i]=0;
        for (j=i;j<=m;j++)
            Sum += a[i][j]*x[j];
        x[i]=(b[i]-Sum)/a[i][i];
    }
    
    cout<<endl;
    
    return x;
    
    for (i=0;i<=m;i++)
    {delete a[i];}
    delete a,x,b;
    

}

int main(){

    const int m=3,n=3; //row,col
    double **amatrix,*bmatrix;
    
    amatrix=new double * [m+1];
    bmatrix=new double  [m+1];
    
    for (int i=0;i<n;i++)
    {
         amatrix[i]=new double [n+1];
    }
    
    //double amatrix[m][n],bmatrix[m];
    
    for (int j=0;j<m;j++)
    {
        bmatrix[0]=2;bmatrix[1]=10;bmatrix[2]=4;
        for (int i=0;i<n;i++)
        {
            amatrix[0][0]=10;amatrix[0][1]=2;amatrix[0][2]=3;
            amatrix[1][0]=2;amatrix[1][1]=1;amatrix[1][2]=2;
            amatrix[2][0]=3;amatrix[2][1]=50;amatrix[2][2]=2;
        }
    }
    
    matrix matrix1;
    matrix();
    matrix(m,n);
    
    for (int i=0;i<m;i++)
        {cout<<matrix1.gaussElimination(amatrix,bmatrix,matrix1)<<endl;}
    
    for (int i=0;i<=m;i++)
    {delete amatrix[i];}
    delete amatrix,bmatrix;
    

}

推荐答案


这篇关于我尝试使用类概念为3 * 3矩阵编写高斯消除程序。但是这段代码每次显示0 0 0结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 17:39