How to code a function that finds roots of numbers?

I'm making a calculator and have so far made addition, subtraction, division, multiplication, raise to the power, and fractorial, but I want to make the option of finding the roots of numbers like: fourth root of 16 which is 2 and I'd like to write a formula that allows me to take any root of any number like root 78.342 of 2.098E23. Does anyone have any idea on how to code this? I tried to write the function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
using namespace std;

float root( float answer, float second, float first );

int main()
{
	float first, second, answer = .1, result;
	
	cout << "Enter first number: ";
	cin >> first;
	cout << "Enter second number: ";
	cin >> second;
	
	root( answer, second, first);

	result = root( answer, second, first );

	cout << "The answer is: " << result << endl;

	return 0;
}

float root( float answer, float second, float first )
{
	
	if( answer >= first )
	return answer;
	else
	{
		
	
		if( second == 1 )
		return 1;
		else
                {
                (answer + .1);
		return  answer * root( answer, second-1, first );
                }
	}
}		
		

as a permutaion to a higher number, but it just gives me .1 as the answer. What am I doing wrong?
Your parameters for root make little sense - the only components needed for the calculation of a root is the radicand and the degree - no "answers", no "firsts" and no "seconds" are involved.
Also, float is bad news. With only 32 bits to work with, it's terribly inaccurate. Use double (which has 64 bits) whenever feasible.

There's a much easier method of calculating a root:
1
2
3
4
double root(double radicand,double degree)
{
  return pow(radicand,1.0/degree);
}
Last edited on
Thanks Athar,
That's exactly what I was looking for :)
Topic archived. No new replies allowed.