我的问题标题可以改进,如果我要谈论的内容有一个具体的名称,请告诉我。
这也不适用于特定语言,我使用的所有语言都将函数调用视为表达式。
所以我一直在阅读递归和尾调用,所以我用 C++ 编写了这段代码
#include <iostream>
using std::cout;
int test(int num) {
if (num > 0) {
return test(num - 1);
}
}
int fact(int num) {
return num == 0 ? 1 : num*fact(num - 1);
}
int main() {
cout << test(20) << '\n';
return 0;
}
当然test(num)
总是会评估0
if num > 0
,因为基本情况是n = 0
。
但为什么?语言如何知道应该返回什么?它如何知道test(n - 1)
应该评估什么?
编辑;
我已经包含了一种获取数字阶乘的递归方法。C++(或任何语言)如何知道乘以num
什么?