gpt4 book ai didi

c++ - 在循环中调用递归函数

转载 作者:太空狗 更新时间:2023-10-29 23:33:43 24 4
gpt4 key购买 nike

当我在循环中调用递归函数时遇到两个问题。考虑以下示例代码:

int fact(int x)
{
if(x == 1)
return 1;
return x*fact(x-1);
}

int main() {
int n = 2;
for(int i = 0; i < n; i++);
std::cout << fact(4) << std::endl; // 24 ??
return 0;
}

问题 1: 我对该程序的预期结果是 24 24(两次 24 是打印机)但我得到的实际结果只有一个 24

问题2:即使我没有递归调用main函数,main()函数重复调用的原因是什么。

如果有人能给我关于如何在循环内调用递归函数以获得多个输出的想法,那就太好了。

最佳答案

for(int i=0; i < n; i++); <---------------------- notice this
std::cout << fact(4) << std::endl; // 24 ??

注意 ;for 循环之后。这就是为什么你只得到一个输出的原因。 std::cout 在循环退出后执行;它在循环的之外

这是第一个问题的答案。现在第二个问题:

What is the reason for the main() function called repetitively even I'm not recursively called the main function.

我认为您发布的代码没有这个问题。您必须在未发布的代码中执行其他操作,因此 main() 被递归调用。

请注意,C++ 语言规范禁止您的 代码调用main()(递归或其他方式)。因此,如果您使用 GCC 的 -pedantic 选项编译它,那么如果您偶然从您的程序中调用 main(),它就不会编译。

关于c++ - 在循环中调用递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10472180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com