这是一个使用递归查找阶乘的程序&我不知道为什么这个程序输出错误。
#include<iostream>
#include<conio.h>
using namespace std;
class factorial
{
public:
int fact(int n)
{
if (n==0)
{
cout<<"1";
}
else
return n * fact(n-1);
}
};
int main()
{
factorial s;
s.fact(5);
getch();
return 0;
}
程序最明显的问题是格式错误:如果n == 0
,int fact(int n)
函数不会返回值。正确的、形成良好的解决方案是:
int fact(int n)
{
if (n == 0) return 1;
return n * fact(n - 1);
}
考虑一下您的基本情况,即n == 0
的情况,它应该返回值1。在主函数中,您永远不会输出函数返回的值。
代替s.fact(5);
尝试cout<< s.fact(5);