写了一小段,错误太多,没信心了,谁能帮帮我!

#include<iostream>
using namespace std;
class Matrix{
float* a;
int m,n;
public:
Matrix(float* s,int y,int z)
{
this->a = a;
m = y;
n = z;
a = new float [m][n];
for(int i = 0 ; i<m; i++)
for(int j = 0 ; j<n ; j++)
a[i][j] = s[i][j];

}
~Matrix
{
for(int i = 0 ; i<m ; i++)
delete []p[i];
}
Matrix& operator=(Matrix& d)
{
for(int i = 0 ; i<m; i++)
for(int j = 0 ; j<n ; j++)
*(a+i)+j = d.a[i][j];
return *this;
}

};

void Input(float* s,int m,int n)
{
for(int i = 0 ; i<m ; i++)
for(int j = 0; j<n ; j++)
cin>>a[i][j];
}

int main()
{

int m,n;
cout<<"请输入矩阵的行数及列数:";
cin>>m>>n;
float s[m][n],d[m][n];
Input(s,m,n);
Input(d,m,n);
Matrix a(s,m,n);
Matrix b(d,m,n);
Matrix c(s,m,n);
b = a;

c = a + b;
c = a - b;
return 0;
}

慕容3067478
浏览 104回答 1
1回答

绝地无双

用一维数组通过下标映射来实现二维数组要简单些。例如,假设a为一个具有m*n个元素的一维数组,则*(a+i*n+j)可以看成是具有m行n列的二维数组的第m行第n列的元素。下面是完整程序:#include<iostream>using namespace std;class Matrix{float* a;int m,n;public:Matrix(float* s=0,int y=0,int z=0){//this->a = a;m = y;n = z;if(m==0 || n==0)a=0;else{a = new float[m*n]; //[m][n];for(int i = 0 ; i<m; i++)for(int j = 0 ; j<n ; j++)*(a+i*n+j)=*(s+i*n+j); //a[i][j] = s[i][j];}}Matrix(Matrix& s){ //拷贝构造函数m=s.m;n=s.n;a = new float[m*n]; //[m][n];for(int i = 0 ; i<m; i++)for(int j = 0 ; j<n ; j++)*(a+i*n+j) = *(s.a+i*n+j);}~Matrix() //(){// for(int i = 0 ; i<m ; i++)delete[] a; //p[i];}Matrix& operator=(Matrix& d){if(&d==this)return *this;if(a!=0)delete[] a;m=d.m;n=d.n;a = new float[d.m*d.n];for(int i = 0 ; i<m; i++)for(int j = 0 ; j<n ; j++)*(a+i*n+j)=*(d.a+i*n+j); //*(a+i)+j = d.a[i][j];return *this;}Matrix operator+(Matrix& d){Matrix temp(a,m,n);for(int i = 0 ; i<m; i++)for(int j = 0 ; j<n ; j++)*(temp.a+i*n+j) =*(a+i*n+j) + *(d.a+i*n+j);return temp;}Matrix operator-(Matrix& d){Matrix temp(a, m, n);for(int i = 0 ; i<m; i++)for(int j = 0 ; j<n ; j++)*(temp.a+i*n+j) -= *(d.a+i*n+j);return temp;}void display(){if(m==0 || n==0){cout <<"该矩阵没有元素\n";return;}for(int i = 0 ; i<m; i++){for(int j = 0 ; j<n ; j++)cout <<*(a+i*n+j) <<" ";cout <<endl;}}};void Input(float* s,int m,int n){cout<<"请输入" <<m <<"*" <<n <<"矩阵:";for(int i = 0 ; i<m ; i++)for(int j = 0; j<n ; j++)cin>> *(s+i*n+j); //a[i][j];}int main(){int m,n;cout<<"请输入矩阵的行数及列数:";cin>>m>>n;float *s, *d; //s[m][n],d[m][n];s=new float[m*n];d=new float[m*n];Input(s,m,n);Input(d,m,n);Matrix a(s,m,n);Matrix b;Matrix c(s,m,n);cout <<"Matrix a:\n";a.display();cout <<"Matrix b:\n";b.display();cout <<"Matrix c:\n";c.display();b = a;cout <<"Matrix b (=a):\n";b.display();c = a + b;cout <<"Matrix c (=a+b):\n";c.display();c = a - b;cout <<"Matrix c (=a-b):\n";c.display();delete[] s;delete[] d;return 0;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

CSS3
Java