2014-07-16 55 views
1

好了,所以我读的程序来创建这里给出你自己的幂函数(Write a C program to calculate pow(x,n)运行时错误来创建自己的电源功能

我读它,它使用此函数计算功耗第1种方法:

int power(int x, unsigned int y) 
{ 
    if(y == 0) 
     return 1; 
    else if (y%2 == 0) 
     return power(x, y/2)*power(x, y/2); 
    else 
     return x*power(x, y/2)*power(x, y/2); 

} 

我得到了这个程序的概念,它给出了正确的结果。

现在,这里power(x, y/2)*power(x, y/2)是这样写的,所以我们只是计算了power(x,y/2)的平方。所以,如果我的power()功能是正确的,所以我可以将其更改为power(power(x,y/2),2)。也就是说,我们只是计算了power(x,y/2)的平方。

所以,当我改变我的程序是:

int power(int x, unsigned int y) 
{ 
    if(y == 0) 
     return 1; 
    else if (y%2 == 0) 
     return power(power(x, y/2),2); // Square of power(x,y/2) 
    else 
     return x*power(power(x, y/2),2); // x*Square of power(x,y/2) 

} 
int main() 
{ 
    int x = 2; 
    unsigned int y = 3; 

    printf("%d\n", power(x, y)); 
    return 0; 
} 

上述计划为运行时错误

什么可能是运行时错误的原因,我无法弄清楚。任何人都可以帮助我吗?

+0

您传递给此函数的输入是什么?当然,提供完整的程序本来很容易,所以我们不必猜测。 –

+0

@DavidHeffernan更新 – Jerky

+2

堆栈溢出,因为您从内部调用函数'power',将第二个参数传递为'2'。 –

回答

4

您从内部调用函数power,传递2作为第二个参数。

这本质上是一个无限递归,最终导致堆栈溢出


如果你的输入参数是一个非负整数,那么你可以如下实现它:

递归:

unsigned long long power(unsigned long long x,unsigned int y) 
{ 
    if (y == 0) 
     return 1; 
    return power(x,y/2)*power(x,y-y/2); 
} 

迭代:

unsigned long long power(unsigned long long x,unsigned int y) 
{ 
    unsigned long long res = 1; 
    while (y--) 
     res *= x; 
    return res; 
} 

高效地:

unsigned long long power(unsigned long long x,unsigned int y) 
{ 
    unsigned long long res = 1; 
    while (y > 0) 
    { 
     if (y & 1) 
      res *= x; 
     y >>= 1; 
     x *= x; 
    } 
    return res; 
} 
+0

对于三种方法,+1 – ryyker

+0

@ryyker:谢谢:) –