I'm trying to write a function that accepts two type double parameters. The function is suppose to be calculate and return a base number raised to an exponent (using recursion), but I can't use the pow() function itself.

I've got it working fine without using decimal format numbers, but i'm stuck on what to do since both parameters accept type double.

This is what i got so far :

``````#include <iostream>

using namespace std;

double recursion (double x, double y)
{

if(y > 1)
return x * recursion(x, y - 1);

else
return x;
}

int main()
{
double base;
double exp;

cout << "(A) raised to the (B) power is ..." << endl;
cout << "Enter input (A): ";
cin >> base;
cout << "Enter input (B): ";
cin >> exp;
// Recursion call

cout << base << " raised to the " << exp <<" power is " << recursion(base, exp) << endl;

return 0;
}``````

any suggestions?

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by nezachem

I don't understand what the problem is. Your program runs ok for me. If you are concerned about it displaying the return value in scientific notation, add `<< fixed` before the call to recursion function.

For example, in my program if you try 2.34 raised to the 3.52 power, you will get a result of 29.9822. This is wrong. The correct answer is 19.9360.

I don't know what I must do so the exponential number can be a decimal and still return the correct answer.

Your approach indeed doesn't work for non-integer exponents. It is just not applicable.
Check out Taylor series, or some other approximation.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.