Reputation: 21
First, I would like to say this is my first attempt at doing a recursive function for my programming class! Anyways, the assignment is to find the root of any positive integer using recursion (absolutely no iteration). My code correctly evaluates the square root of any positive number, but when I try to take say the fourth root or third root of a number I get a stack overflow error. I will post my code and any help would greatly be appreciated. Blast away if you feel need hah.
#include<iostream>
#include<iomanip>
#include<cstdlib>
using namespace std;
double squareRoot (int root, double number, double low, double high);
int main() {
int root = 0;
double number;
double low, high;
double guess = 0;
double error = 0;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
do
{
cout << "Find what root? (0 ends): ";
cin >> root;
if (root == 0)
{
exit(1);
}
else
{
cout << "Root of what value? ";
cin >> number;
}
low = number - (number - 1);
high = number;
cout << "root " << root << " of " << setprecision(4) << number << " is " << setprecision(10) << squareRoot (root, number, low, high) << endl;
}while (root != 0);
cin.get();
cin.get();
return 0;
}
double squareRoot (int root, double number, double low, double high)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(10);
double guess = (high + low) / double(root);
double error = abs(number - (guess * guess));
if ((guess * guess) == number || error <= 0.000000000001)
{
return guess;
}
else if ((guess * guess) > number)
{
high = guess;
return squareRoot(root, number, low, high);
}
else
{
low = guess;
return squareRoot(root, number, low, high);
}
}
Upvotes: 2
Views: 274
Reputation: 86708
Here's a hint:
You function is called squareRoot
and it contains guess * guess
in several places, so what is the int root
parameter for?
Upvotes: 0
Reputation: 8895
You have an issue in the recursion, a stack overflow is a common issue with recursive functions, your exit condition is probably faulty.
As already stated above, take a pencil & paper and start diggin.
Upvotes: 1
Reputation: 76898
You're getting a stack overflow because you are infinitely recursing; you never find the answer.
Take a pencil and paper, and walk through your recursion with an input (say 3 for root and 8 for value) ... figure out why your solving logic isn't working.
Upvotes: 3