这题要求必须用递归函数,本人知道不能一半在函数外一半在函数里算,但本人想知道哪里错了。
1,2,3,的阶乘都是正确的,但从4开始都是0了。
#include<iostream>
double song(int x,double y);
int main()
{
using namespace std;
int x=0;
double y=1;
cout<<“Please enter an integer:”;
while(cin>>x)
{
if(x==0||x==1)
cout<<x<<“!=1″<<endl;
else
{
y=x*(x-1);
cout<<x<<“!=”<<song(x-1,y)<<endl;
}
cout<<“Please enter next integer:”;
}
cin.get();
cin.get();
return 0;
}
double song(int x,double y)
{
if(x>1)
{
y*=(–x);
song(x,y);
}
if(x==1)
return y;
}
1,2,3,的阶乘都是正确的,但从4开始都是0了。
#include<iostream>
double song(int x,double y);
int main()
{
using namespace std;
int x=0;
double y=1;
cout<<“Please enter an integer:”;
while(cin>>x)
{
if(x==0||x==1)
cout<<x<<“!=1″<<endl;
else
{
y=x*(x-1);
cout<<x<<“!=”<<song(x-1,y)<<endl;
}
cout<<“Please enter next integer:”;
}
cin.get();
cin.get();
return 0;
}
double song(int x,double y)
{
if(x>1)
{
y*=(–x);
song(x,y);
}
if(x==1)
return y;
}
解决方案
20
#include<iostream> double song(int x,double& y); int main() { using namespace std; int x=0; double y=1; cout<<"Please enter an integer:"; while(cin>>x) { if(x==0||x==1) cout<<x<<"!=1"<<endl; else { y=x*(x-1); cout<<x<<"!="<<song(x-1,y)<<endl; } cout<<"Please enter next integer:"; } cin.get(); cin.get(); return 0; } double song(int x,double& y) { if(x>1) { y*=(--x); song(x,y); return y; } if(x==1) return y; }
两个错误,一个是y必须传引用,二是返回点不对