【发布时间】:2016-10-14 21:05:54
【问题描述】:
我没有在 C++ 中得到这个递归练习。这里是:
int fatt(int x){
int s=1; // here. since 's' will always be 1 shouldn't i get 1 as an output???
if(x>1) { s = x*fatt(x-1); }
return s;
}
int main()
{
int n;
cout << "Type a number: ";
cin >> n;
if (n < 0) { cout << "Error" << endl; }
if (n <=1) { cout << "Factorial: 1" << endl; }
else { cout << "Factorial: " << fatt(n) << endl; }
}
如果我输入s=0,它总是将我作为输出返回0,如果我输入 2,它会使结果加倍 O.o 我不明白它是如何工作的。我知道x 总是会减少直到达到 2 并且返回结果但是每次调用函数时不应该给 's' 的值 1???
【问题讨论】:
-
"'s' 不应该被赋予 1 的值???"是的,但是下一行给
s分配了其他东西,所以不,它并不总是返回 1。 -
当你调用 fatt(3) 时,x 不会改变。 fatt(3) 的执行调用了 fatt(2),创建了一个新的上下文,其中另一个变量也名为 x,但不同。
-
递归的可视化有时会有所帮助:mrlamont.com/uploads/1/7/0/2/17021682/factorial.png
-
如果你理解了代码:你不需要做 if (n
-
哇谢谢大家!图片实际上对我帮助很大! ^^
标签: c++ function recursion return