【发布时间】:2016-01-07 06:34:04
【问题描述】:
// 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;
}
我在学校学习编程课程。这是书中给出的递归函数的示例。我不太清楚他们在做什么以及所涉及的技术。我只是想知道是否有人可以向我解释这一点,或者至少为我指明正确的方向,以便我更好地理解这种技术。
【问题讨论】:
-
为什么不用铅笔和一张纸,用
x和n的值写出幂的步骤,得到x和n的新值得到了解正在发生的事情 -
问问你的讲师/老师,他们会为你解释的。
-
老师似乎没有直接解决手头的问题,我觉得这本书没有解释清楚。我从这个网站找到了更好的答案和理解。
-
作为获得更多理解的另一种策略:使用您的调试器逐行单步执行代码(单步执行函数调用)。如果您不知道该怎么做:现在是学习如何使用调试器的好时机。提示:如果您的调试器支持它(例如 Visual Studio),也让它显示调用堆栈并注意它是如何变化的。
-
@jxh - “向我解释这段代码”问题与程序员无关。