我正在编写一个具有递归函数的代码。但是它执行了两次,实际上我知道它为什么会发生但是我想阻止它请帮助......
int getMatrices()
{
cout<<"Enter The Number Of Rows Of First Matrix : ";
cin>>row_a;
cout<<"Enter The Number Of Column Of First Matrix : ";
cin>>column_a;
cout<<"Enter The Number Of Rows Of Second Matrix (Can Not Be Different From Number Of Column Of First): ";
cin>>row_b;
cout<<"Enter The Number Of Column Of First Matrix : ";
cin>>column_b;
this->checkPhysibility(column_a, row_b);
cout<<"\nEnter the first matrix : \n";
fsor(int i=0;i<row_a;i++)
for(int j=0;j<column_a;j++)
{
cout<<"\tA("<<i+1<<", "<<j+1<<") : ";
cin>>a[i][j];
}
cout<<"\nEnter the second matrix : \n";
for(int i=0;i<row_b;i++)
for(int j=0;j<column_b;j++)
{
cout<<"\tB("<<i+1<<", "<<j+1<<") : ";
cin>>b[i][j];
}
}
int checkPhysibility(int column_a, int row_b)
{
if(column_a!=row_b)
{
cout<<"\n\nYou Entered Wrong Input, The Number Of Column Of First Matrix Can Not Be Different From Row Of Second Matrix For Making Their Multiplication Physible. Please Re-Enter The Values.\n\n";
this->getMatrices();
}
}
在调用checkPhysibility方法之后,它会检查它,但是如果进入if语句并再次执行getMatrices它会产生一个递归链,并且getMatrices函数中的代码(在checkPhysibility调用之后)执行两次我想要破解。 return语句不起作用....
答案 0 :(得分:2)
checkPhysibility
的返回类型更改为bool
。getMatrice
具有获取数据和写入消息的所有代码,因此在该函数中打印消息更有意义。getMatrices
返回checkPhysibility
,则将false
更改为返回。checkPhysibility
更改为checkFeasibility
。bool checkFeasibility(int column_a, int row_b)
{
return (column_a == row_b);
}
int getMatrices()
{
cout<<"Enter The Number Of Rows Of First Matrix : ";
cin>>row_a;
cout<<"Enter The Number Of Column Of First Matrix : ";
cin>>column_a;
cout<<"Enter The Number Of Rows Of Second Matrix (Can Not Be Different From Number Of Column Of First): ";
cin>>row_b;
cout<<"Enter The Number Of Column Of First Matrix : ";
cin>>column_b;
if ( false == checkFeasibility(column_a, row_b) )
{
cout<<"\n\nYou Entered Wrong Input, The Number Of Column Of First Matrix Can Not Be Different From Row Of Second Matrix For Making Their Multiplication Physible. Please Re-Enter The Values.\n\n";
// ???
return 0;
}
cout<<"\nEnter the first matrix : \n";
fsor(int i=0;i<row_a;i++)
for(int j=0;j<column_a;j++)
{
cout<<"\tA("<<i+1<<", "<<j+1<<") : ";
cin>>a[i][j];
}
cout<<"\nEnter the second matrix : \n";
for(int i=0;i<row_b;i++)
for(int j=0;j<column_b;j++)
{
cout<<"\tB("<<i+1<<", "<<j+1<<") : ";
cin>>b[i][j];
}
// ???
return 1;
}
答案 1 :(得分:0)
简短的回答是通过&#34;深度&#34;参数。每次调用增加1。然后你知道函数在哪个级别。
答案很长,这不是一种使用递归的好方法。如果用户输入错误,请跳回循环以重新输入。不要尝试使用递归进行循环,至少在C / C ++中。一些编程Lisp的人会以不同的方式告诉你。