简体   繁体   English

C++ 中的递归幂函数

[英]Recursive power function in C++

I'm having some trouble with this function.我在使用此功能时遇到了一些问题。 The function takes a and computes it to the power of b recursively.该函数采用 a 并以递归方式将其计算为 b 的幂。 My compiler gives me a segmentation error when I compile this, which I'm not sure how to fix.我的编译器在编译时给了我一个分段错误,我不知道如何解决。 Can anyone help?任何人都可以帮忙吗?

/****   Recursive power function   > Computes a^b, where b can be positive or negative*****/
        int recPower(double a, int b)
        {   
            if (b == 0)
            {
                return 1;
            }
            else
            {
                return (a *recPower(a, b-1));
            }
          }

/* Computes a^b (power function) */    
cout << "POWER" << endl;    
cout << "----------" << endl;    
int a = 2, b = -3;    
cout << a << "^" << b << " = ";    
cout << recPower(a, b) << endl;    
cout << endl;    

The crash is a result of infinite recursion.崩溃是无限递归的结果。 b never reaches 0 since you keep decrementing it on every recursive step. b永远不会达到 0,因为您在每个递归步骤中都不断递减它。

You probably need to insert this clause into your code:您可能需要将此子句插入到您的代码中:

if (b < 0)
{
    return 1.0 / recPower(a,-b);
} 
else if (b == 0)
...

Of course, a to the power of a negative number will more sure be a value between 0 and 1, which is hard to reflect accurately if your return type is int.当然,a 的负数次方更确定是 0 到 1 之间的值,如果您的返回类型是 int,则很难准确反映。 That's an exercise left up to you to reconcile.这是一个由你来协调的练习。 recPower should probably return a double type if the input parameter is a double.如果输入参数是双recPower型, recPower可能应该返回双recPower型。

As divx commented, the problem is that your funtion doesn't work well with negative expontents: it enters in an infinite recursion (not exactly infinite, but it causes an stack overflow).正如 divx 评论的那样,问题在于您的函数不能很好地处理负指数:它进入无限递归(不是完全无限,但会导致堆栈溢出)。

Other thing, is that if the base is double or you want to process negative exponents, then the function should return a double .另一件事是,如果基数为double或您想处理负指数,则该函数应返回double

This will do the work:这将完成以下工作:

double recPower(double a, int b)
{
    if (b < 0)
    {
        return 1.0/recPower(a, -b);
    }
    else if (b == 0)
    {
        return 1;
    }
    return (a *recPower(a, b-1));
}

Output for your example:您的示例的输出:

POWER
----------
2^-3 = 0.125

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM