gpt4 book ai didi

c - 为什么这个 C 程序在函数作为参数调用时表现异常

转载 作者:行者123 更新时间:2023-12-02 02:53:53 24 4
gpt4 key购买 nike

我创建了一个程序来计算一个数的幂。请查看工作代码:

    #include <stdio.h>
#include <stdlib.h>

int power(int,int);

int main()
{
int num,n;
scanf("%d %d",&num,&n);
printf("power of %d to %d\n",num,n);

printf("%d",power(num,n));
return 0;
}

int power(int num,int n)
{
int result=0;
if(n==0)
return 1;
if(n==1)
return num;
if(n%2!=0)
{
result=num*power(num,n-1);
}
else if(n%2==0)
{
result=power(num,n/2)*power(num,n/2);
//why this hangs when i replace this statement with power(power(num,n/2),2)
}

return result;
}

只要我不将最后一条语句替换为评论中提到的语句,该程序就可以正常工作。

能否请您告诉我这种异常行为背后的原因?

最佳答案

This program works fine as long as I don't replace the last statement with the one mentioned in the comments.

Could you please let me know the reason behind this abnormal behaviour?

这不是异常行为。

power(power(num,n/2),2)

是一个递归调用,其中永远不会达到基本情况,因为 n == 2 因此 n % 2 == 0 的 else if 子句总是执行。

关于c - 为什么这个 C 程序在函数作为参数调用时表现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50542486/

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