Derp
Derp

Reputation: 929

Recursive Power Function

I'm trying to write a recursive power function without using math.h / pow(), but I keep getting garbage values of -1.#IND. I think i'm missing something when I call for a new instance of the power function, but I don't quite understand how to get around it. My full code is fairly short:

#include <iostream>
using namespace std;

double power(double b, int e){
    double x;

    if(e == 0){
        x = b;
    }
    else if(b == 0){
        x = 1;
        e = 0;
    }
    else if(e < 0){
        x = (1 / b) * power(b, ++e);
    }
    else{
        x = b * power(b, --e);
    }

    return x;
}

int main(){
    double num;
    int exp;

    cout << "Please Enter Your Number: ";
    cin >> num;

    cout << "Please Enter The Explonent: ";
    cin >> exp;

    cout << power(num, exp);
    cin >> num;
}

Upvotes: 0

Views: 4663

Answers (3)

David Hammen
David Hammen

Reputation: 33126

You might have accepted an answer prematurely. Your code still has problems (2^-3 returns .25) and your code is highly suboptimal. You should be able to compute 1.000001^1000000 with ease (it's very close to e), but your algorithm will segfault because it requires a stack depth of about a million. For example, computing a^1024 can be done with only 10 multiplications instead of 1023.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490663

The only place you return a value from power is where e==0.

The other cases compute values, but never return them.

Upvotes: 4

Daniel
Daniel

Reputation: 31609

You forgot returns. Turn on compiler warnings and it will complain.

Upvotes: 3

Related Questions