Reputation: 105
I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.
#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--));
}
Upvotes: 0
Views: 2217
Reputation: 100
Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.
X ^ 0 = 1
The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.
float power(float a, int b)
{
int bx = -b ? b < 0 : b;
if (bx == 0)
{
a = 1;
return a;
}
return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}
Upvotes: 0
Reputation: 61
if ( b <= 0) return 1;
return a * power(a, --b);
But this question was asked so many times....
Recursion function to find power of number
Upvotes: 1
Reputation: 5321
Instead of b--
you need b-1
(or --b
)
b--
reduces b
by one, which has no effect because that instance of b
is never used again. It passes the unreduced copy of b
recursively.
Also, when b
is zero, the result should be 1
rather than a
Upvotes: 7