We're supposed to write a program that will approximate a square root using a recursive function. For some reason, I cannot get it to return the proper numbers. I ran an error check using some printf's and it seems like the lower value is not being replaced when it should be. Can anyone help me out? Here is my function:
double square_root(double low, double high)
mid = (high + low) / 2;
if((mid*mid) == high)
//Stops when the high and low numbers are within 0.001 of one another.
if((high - low) < 0.001)
if((mid*mid) > high)
return square_root(low, mid);
return square_root(mid, high);
I don't understand your logic. Which variable holds the number you are wanting the square root of?
Well, the question is: once you are inside the function, how do you know what number you're trying to take the square root of? (Answer: you don't, but you really should.)
I mean, say we're trying to find the square root of 10 and we pass 0, 10 as arguments. Then mid is 5, 5*5 > 10, so we call square_root(0,5) and all of a sudden we're trying to find the square root of 5.
Oh, sorry. The number is getting passed into the high value. Here is my main:
double square_root(double low, double high);
printf("Enter a number to compute the square root of.\n");
root = square_root(1, number);
printf("The square root of %.3f is about %.3lf\n", number, root);
You would do good to rename your variables to something like this:
or something more meaningful than low and high. Low and high, to me, represent guesses.
double square_root(double current_guess, const double number);
Yes; well, as we mentioned, it's not going to stay there. You're probably going to need three function parameters if you want to do this recursively.
Originally Posted by MiroMage
Oh wow. Haha. Thanks guys. I can't believe I didn't see that.
It's been a long night. Thanks again. ^_^