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?

Recommended Answers

All 3 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.