问题描述
- 求大神解答一下c++的题,重载运算符+,-,*,求矩阵的运算,做了好久没做出来
-
#include<iostream.h> #include<iomanip.h> class operation {public: static void rank(); //输入阶数 void array(); //输入矩阵 void display(); friend operation operator +(operation &,operation &); friend operation operator -(operation &,operation &); friend operation operator *(operation &,operation &); private: int a[50][50]; static int n; }; void operation::rank() {cin>>n;} void operation::array() { for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin>>a[i][j]; } operation operator +(operation &a1,operation &a2) { operation a3; for(int i=0;i<operation::n;i++) for(int j=0;j<operation::n;j++) a3.a[i][j]=a1.a[i][j]+a2.a[i][j]; return a3; } operation operator -(operation &a1,operation &a2) { operation a3; for(int i=0;i<operation::n;i++) for(int j=0;j<operation::n;j++) a3.a[i][j]=a1.a[i][j]-a2.a[i][j]; return a3; } operation operator *(operation &a1,operation &a2) { operation a3; for(int k=0;k<operation::n;k++) { for(int i=0;i<operation::n;i++) { for(int j=0;j<operation::n;j++) a3.a[k][i]+=a1.a[k][j]*a2.a[j][i]; } } return a3; } void operation::display() { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) cout<<setw(10)<<operation::a[i][j]; cout<<endl; } } int operation::n; #include"operation.h" int main() { operation a1,a2,a3; cout<<"piease input rank:"; operation::rank(); cout<<"please input a1:"<<endl; a1.array(); cout<<"please input a2:"<<endl; a2.array(); cout<<"a1+a2:"<<endl; a3=a1+a2; a3.display(); cout<<"a1-a2:"<<endl; a3=a1-a2; a3.display(); cout<<"a1*a2:"<<endl; a3=a1*a2; a3.display(); return 0; }
解决方案
什么情况,我看没问题啊,输出不对?
解决方案二:
看上去没什么问题
是运行乘法的时候报错还是输出结果不对?
解决方案三:
未看出问题,乘法运算出错了吗?如果不对,建议你单步调试一下,应该很快就能找到问题的原因
时间: 2024-12-30 10:41:27