gpt4 book ai didi

C 代码 : Passing expression as an argument in recursion call

转载 作者:太空宇宙 更新时间:2023-11-04 05:26:24 25 4
gpt4 key购买 nike

我在练习一些 C 问题时遇到了一个场景,其中递归函数使用表达式作为参数调用自身。

Pow(double x, unsigned n){ 
.....
.....
return Pow(x*x,n/2);
}

我的问题是参数是在评估表达式时传递的(x*x,如在按值调用中)还是这是一个惰性评估,即直到使用时才评估。

下面是问题的详细内容

查找调用 Pow(5.0,12) 后的乘法次数?

Pow(double x, unsigned n) { 
if(n==0) return 1;
if(n==1) return x;
if(n%2==0) return Pow(x*x,n/2);
else
return Pow(x*x,n/2)*x;
}

选项 5,6,8,12

最佳答案

C 中函数的所有参数都在函数被调用之前计算。

您示例中的评估和调用:

Pow(5, 12) = Pow(5 * 5, 6) = 
Pow(25, 6) = Pow(25 * 25, 3) =
Pow(625, 3) = Pow(625 * 625, 1) * 625

关于C 代码 : Passing expression as an argument in recursion call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25744854/

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