主题:[原创]求N阶方阵的n次方
上次的程序修正过了,现在可以实现了。
#include<iostream>
using namespace std;
#define N 3
class Matrix
{
int m[N][N];
public:
Matrix();
Matrix(int init);
void print();
friend Matrix operator *(Matrix ma,Matrix mb);
friend Matrix operator ^(Matrix mat,int n);
};
Matrix::Matrix()
{
int i,j;
for(i=0;i<N;++i)
for(j=0;j<N;++j)
cin>>m[i][j];
}
Matrix::Matrix(int init)
{
int i,j;
for(i=0;i<N;++i)
for(j=0;j<N;++j)
m[i][j]=init;
}
void Matrix::print()
{
int i,j;
for(i=0;i<N;++i)
{
for(j=0;j<N;++j)
cout<<m[i][j]<<'\t';
cout<<endl;
}
}
Matrix operator *(Matrix ma,Matrix mb)
{//两个方阵相乘
int i,j,k;
Matrix result(0);
for(i=0;i<N;++i)
for(j=0;j<N;++j)
for(k=0;k<N;++k)
result.m[i][j]=result.m[i][j]+ma.m[i][k]*mb.m[k][j];
return result;
}
Matrix operator ^(Matrix mat,int n)
{//方阵的n次
Matrix result(0);
result=mat;
for(int i=0;i<n-1;++i)
result=result*mat;
return result;
}
void main()
{//求N阶方阵的n次方
int n;
cout<<"n=";
cin>>n;
cout<<N<<"阶方阵为:"<<endl;
Matrix matrix,result(0);
result=matrix^n;
cout<<"已知的"<<N<<"阶方阵的"<<n<<"次方为:"<<endl;
result.print();
}
#include<iostream>
using namespace std;
#define N 3
class Matrix
{
int m[N][N];
public:
Matrix();
Matrix(int init);
void print();
friend Matrix operator *(Matrix ma,Matrix mb);
friend Matrix operator ^(Matrix mat,int n);
};
Matrix::Matrix()
{
int i,j;
for(i=0;i<N;++i)
for(j=0;j<N;++j)
cin>>m[i][j];
}
Matrix::Matrix(int init)
{
int i,j;
for(i=0;i<N;++i)
for(j=0;j<N;++j)
m[i][j]=init;
}
void Matrix::print()
{
int i,j;
for(i=0;i<N;++i)
{
for(j=0;j<N;++j)
cout<<m[i][j]<<'\t';
cout<<endl;
}
}
Matrix operator *(Matrix ma,Matrix mb)
{//两个方阵相乘
int i,j,k;
Matrix result(0);
for(i=0;i<N;++i)
for(j=0;j<N;++j)
for(k=0;k<N;++k)
result.m[i][j]=result.m[i][j]+ma.m[i][k]*mb.m[k][j];
return result;
}
Matrix operator ^(Matrix mat,int n)
{//方阵的n次
Matrix result(0);
result=mat;
for(int i=0;i<n-1;++i)
result=result*mat;
return result;
}
void main()
{//求N阶方阵的n次方
int n;
cout<<"n=";
cin>>n;
cout<<N<<"阶方阵为:"<<endl;
Matrix matrix,result(0);
result=matrix^n;
cout<<"已知的"<<N<<"阶方阵的"<<n<<"次方为:"<<endl;
result.print();
}