0

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--));
}
1
  • pow(a, some_negative_value) == a? What? And how can an unsigned value negative? Commented Sep 20, 2015 at 17:26

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

0

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.

Stopping criteria

X ^ 0 = 1

Unwinding the stack

The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.

  • If A is the base and B the power, as a first step, take the absolute value of B.
  • Secondly, store A in the stack and decrement B. Repeat until B = 0 (stopping criterion). Store the result in the stack.
  • Thirdly, multiply all the A's stored by unwinding the stack.

Now the code

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));
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.