我需要编写一个程序,使用递归函数计算给定数字的幂。我写了这个我无法让它工作,一旦我到达函数本身它就会中断。有什么帮助吗?谢谢。
#include"stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
float power(float a, unsigned int b);
int main()
{
float a = 0;
unsigned int b = 0;
cout << "Insert base - ";
cin >> a;
cout << "Insert index - ";
cin >> b;
float result;
result = power(a, b);
cout << result;
return 0;
}
float power(float a, unsigned int b)
{
if (b <= 0)
{
return a;
}
return (a*power(a, b--));
}
最佳答案
您需要 b-1
(或 --b
)
b--
b--
将 b
减一,这没有任何效果,因为 b
的那个实例再也不会被使用。它以递归方式传递 b
的未缩减拷贝。
此外,当 b
为零时,结果应该是 1
而不是 a
关于c++ - 在 C++ 上使用递归函数计算幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32682044/