递归函数找出数的幂 [英] Recursion function to find power of number
问题描述
我正在写一个递归函数来找到一个数字的强度,它似乎是编译但不输出任何东西。
I'm writing a recursion function to find the power of a number and it seems to be compiling but doesn't output anything.
#include <iostream>
using namespace std;
int stepem(int n, int k);
int main()
{
int x, y;
cin >> x >> y;
cout << stepem(x, y) << endl;
return 0;
}
int stepem(int n, int k)
{
if (n == 0)
return 1;
else if (n == 1)
return 1;
else
return n * stepem(n, k-1);
}
我试过调试它,它说的问题是这行:
return n * stepem(n,k-1);
I tried debugging it, and it says the problem is on this line :
return n * stepem(n, k-1);
k似乎有些奇怪值,但我不知道为什么?
k seems to be getting some weird values, but I can't figure out why?
推荐答案
你应该检查指数k,变化。
You should be checking the exponent k, not the number itself which never changes.
int rPow(int n, int k) {
if (k <= 0) return 1;
return n * rPow(n, --k);
}
你的k值越来越奇怪,因为你会一直计算,直到你用完内存基本上,你会创建许多堆栈帧,k去-infinity(假设)。
Your k is getting weird values because you will keep computing until you run out of memory basically, you will create many stack frames with k going to "-infinity" (hypothetically).
这就是说,理论上可能的编译器给你警告它永远不会终止 - 在这个特定的情况。但是,自然不可能解决这个一般(查找Halting问题)。
That said, it is theoretically possible for the compiler to give you a warning that it will never terminate - in this particular scenario. However, it is naturally impossible to solve this in general (look up the Halting problem).
这篇关于递归函数找出数的幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!