【问题标题】:Runtime error in program to create your own power function程序中的运行时错误以创建您自己的幂函数
【发布时间】:2014-07-16 15:23:02
【问题描述】:

好的,我正在阅读程序来创建您自己的幂函数(Write a C program to calculate pow(x,n)

我读到它是使用此函数计算功率的第一种方法:

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;
}

上面的程序给出了运行时错误

我无法弄清楚运行时错误的原因可能是什么。谁能帮帮我?

【问题讨论】:

  • 你传递给这个函数的输入是什么?当然,提供一个完整的程序是很容易的,这样我们就不必猜测了。
  • @DavidHeffernan 更新
  • 堆栈溢出,因为您从内部调用函数power,将第二个参数作为2 传递。

标签: c math runtime-error


【解决方案1】:

您正在从内部调用函数 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;
}

【讨论】:

  • 三种方法,+1
最近更新 更多