// Ex5_15.cpp (based on Ex5_01.cpp)
// A recursive version of x to the power n
#include <iostream>
using std::cout;
using std::endl;
double power(double x, int n); // Function prototype
int main(void)
{
double x(2.0); // Different x from that in function power
double result(0.0);
// Calculate x raised to powers -3 to +3 inclusive
for(int index = -3; index <= 3; index++)
cout << x << “ to the power “ << index << “ is “ << power(x, index) << endl;
return 0;
}
// Recursive function to compute integral powers of a double value
// First argument is value, second argument is power index
double power(double x, int n)
{
if(n < 0)
{
x = 1.0/x;
n = -n;
}
if(n > 0)
return x*power(x, n-1);
else
return 1.0;
}
我在学校上编程课。这是本书中递归函数的示例。我不太了解他们在做什么以及所涉及的技术。我只是想知道是否有人可以向我解释这一点,或者至少可以指出正确的方向,以便我更好地理解这种技术。
最佳答案
让我们看看调用power(2,3)
会发生什么:
double power(double x, int n) { // x = 2, n=3;
if (n<0) {...} // false, so skip the brackets
if (n>0) // true
return x*power (x; n-1); // call power() again, with different paraleters
... // the rest is skipped
}
因此它返回
2 * power(something)
。在计算返回值之前,power()
必须再次调用自身。这是一个递归调用。您可以看到这就像要执行的函数的另一个副本一样,带有它自己的变量(即不触摸调用实例的局部变量)。因此,现在使用参数x = 2和n = 2调用
power()
。执行流程相似,它将返回2 * power(x, n-1)
,但n-1
现在为1。因此这里再次递归。现在,使用x = 2和n = 1调用
power()
。这将返回2 * power(x, n-1)
,但n-1现在为0。最后,将以x = 2和n = 0调用功率。在这里,执行流程将跳过两个ifs并最终执行执行elese分支,因为n为0。它将返回1。
现在我们有了所有元素,可以通过结束这些连续的调用来计算值
所有这些都可以以图形方式显示:
power(2,3)
|
+--> 2 * power(2,2)
|
+--> 2* power(2,1)
|
+--> 2* power(2,0)
|
1
因此最后返回2 * 2 * 2 * 1,即2 ^ 3,即预期结果。
通过进一步推广这种推理,您可以使用mathematical induction证明对于任何n> = 0,
power (x, n)
将返回x^n
。我让您通过观察当n为负时会发生什么来完成练习。这里的furhter reading可以帮助在不同的视角下进行一些图形化的解释。
关于c++ - 在C++中使用递归函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34643568/