gpt4 book ai didi

c - 下面的递归如何输出48?

转载 作者:行者123 更新时间:2023-11-30 20:55:58 25 4
gpt4 key购买 nike

C 中的以下递归如何输出 48 ?我预计输出为 0。

#include<stdio.h>

int fun(int i) {
if(i<2)
return 1;
else {
return fun(--i) * i * fun(--i);
}
}

int main() {
printf("%d",fun(5));
return 0;
}

最佳答案

表达式fun(--i) * i * fun(--i)表现出未定义的行为。所以我们不能对这会产生什么做出任何假设。如果您好奇为什么它未定义,请阅读: Why are these constructs (using ++) undefined behavior?

我们可以尝试删除未定义的行为,并讨论这一点:

int fun(int i) {
if(i<2)
return 1;
else {
return fun(i - 1) * (i - 1) * fun(i - 2);
}
}

fun(5) 应该并且确实使用正确的代码生成 48。如果我们需要证明......

fun(0) == 1
fun(1) == 1
fun(2) == fun(1) * 1 * fun(0) == 1 * 1 * 1 == 1
fun(3) == fun(2) * 2 * fun(1) == 1 * 2 * 1 == 2
fun(4) == fun(3) * 3 * fun(2) == 2 * 3 * 1 == 6
fun(5) == fun(4) * 4 * fun(3) == 6 * 4 * 2 == 48

关于c - 下面的递归如何输出48?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29239157/

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