我有一个矩阵和向量相乘的代码。但是,它不会 进入友元函数 for
中的
calc()
循环内部。你能发现错误吗?
#include<iostream>
using namespace std;
class vector;
class matrix
{
public:
int r,c,ma[10][10];
void get(int r, int c=3)
{
int i,j;
cout<<"Enter the matrix elements\n";
for(i=0; i<r; i++)
for(j=0; j<c; j++)
{
cin>>ma[i][j];
}
cout<<"Your input: ";
for(i=0; i<r; i++)
{
cout<<"\n";
for(j=0; j<c; j++)
{
cout<<ma[i][j]<<"\t";
}
}
}
friend void calc(matrix m,vector v);
};
class vector
{
public:
int val,va[10];
void get(int v=3)
{
int i;
cout<<"\nEnter the vector values\n";
for(i=0; i<v; i++)
{
cin>>va[i];
}
cout<<"\nYour input:\n";
for(i=0; i<v; i++)
{
cout<<va[i]<<"\t";
}
}
friend void calc(matrix m,vector v);
};
void calc(matrix m,vector v)
{
int c[10],i,j;
if(m.c == v.val)
{
for(i=0; i<v.val; i++)
{
cout<<"Entered 1st loop";
c[i] = 0;
for(j=0; j<m.r; j++)
{
c[i] = c[i]+(m.ma[i][j] * v.va[j]);
}
}
}
cout<<"\nThe result is :\n";
for(i=0; i<m.r; i++)
{
cout<<"Entered for";
cout<<"\n"<<c[i];
}
}
int main()
{
int r;
matrix m1;
vector v1;
cout<<"Enter the number of rows = ";
cin>>r;
m1.get(r);
v1.get();
calc(m1,v1);
return 0;
}
您永远不会在
val
类中初始化 vector
,也不会在 r
类中初始化 c
和 matrix
。因此,检查 if(m.c == v.val)
永远无法通过,因为这些成员的值是 未定义(包含随机垃圾)。
我建议您看一下 The Definitive C++ Book Guide and List;一本好书将帮助您掌握基础知识。
#include<iostream>
#include<math.h>
#include<windows.h>
using namespace std;
class vecter;
class matrix
{
int matrex[3][3];
public:
friend void multiply(matrix &,vecter &);
void setmatrix()
{
cout<<"Enter the elements into the matrix array "<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<"Enter the element in to the "<<i+1<<" row and "<<j+1<<" column "<<endl;
cin>>matrex[i][j];
}
}
}
void dismatrix()
{
cout<<" The elements into the matrix array are "<<endl;
for(int i=0;i<3;i++)
{
cout<<"|";
for(int j=0;j<3;j++)
{
cout<<":"<<matrex[i][j]<<" : ";
}
cout<<"|";
cout<<endl;
}
}
};
class vecter
{
int vector[3];
public:
friend void multiply(matrix &,vecter &);
void setvector()
{
for(int i=0;i<3;i++)
{ cout<<"Enter the "<<i+1<<" element in to the vector Array "<<endl;
cin>>vector[i];
}
}
void disvector()
{
cout<<"The elements in the index of the vector array are "<<endl;
for (int i=0;i<3;i++)
{
cout<<"|"<<vector[i]<<"|"<<endl;
}
}
};
void multiply (matrix &m,vecter &v)
{
int solution[3];
//initilization.
for(int i=0;i<3;i++)
{
solution[i]=0;
}
//multiplication.
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
solution[i]+=( m.matrex[i][j]*v.vector[j]);
}
}
cout<<"\t\t\t\t\t processing..... ";
for(int i=0;i<20;i++)
{
cout<<char(219);
Sleep(200);
}
cout<<endl;
for(int i=0;i<3;i++)
{
cout<<"|"<<solution[i]<<"|"<<endl;
}
}
int main()
{
matrix m;
vecter v;
v.setvector();
m.setmatrix();
m.dismatrix();
cout<<endl;
v.disvector();
multiply(m,v);
system ("pause>0");
}