# Square Roots?

• 09-27-2008
MiroMage
Square Roots?
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:

Code:

```double square_root(double low, double high) {     float mid;         mid = (high + low) / 2;     //Base Case     if((mid*mid) == high)         return mid;     //Stops when the high and low numbers are within 0.001 of one another.      if((high - low) < 0.001)         return mid;         if((mid*mid) > high)         return square_root(low, mid);             return square_root(mid, high); }```
• 09-27-2008
Dino
I don't understand your logic. Which variable holds the number you are wanting the square root of?
• 09-27-2008
tabstop
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.
• 09-27-2008
MiroMage
Oh, sorry. The number is getting passed into the high value. Here is my main:

Code:

```double square_root(double low, double high); int main(void) {     float number;     double root;         printf("Enter a number to compute the square root of.\n");     scanf("%f", &number);         root = square_root(1, number);         printf("The square root of %.3f is about %.3lf\n", number, root);         system("PAUSE");     return 0;```
• 09-27-2008
Dino
You would do good to rename your variables to something like this:

Code:

`double square_root(double current_guess, const double number);`
or something more meaningful than low and high. Low and high, to me, represent guesses.
• 09-27-2008
tabstop
Quote:

Originally Posted by MiroMage
Oh, sorry. The number is getting passed into the high value.

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.
• 09-27-2008
MiroMage
Oh wow. Haha. Thanks guys. I can't believe I didn't see that.

It's been a long night. Thanks again. ^_^