I am trying to write a function to express this but I keep confusing myself. Maybe I am thinking about it too hard?
4.5 is halfway between 1 and 8. 4.52 = 20.25, so the square root of 8 must be less than 4.5.
2.75 is halfway between 1 and 4.5. 2.752 = 7.5625, so the square root of 8 must be greater than 2.75.
3.625 is halfway between 2.75 and 4.5. 3.6252 = 13.140625, so the square root of 8 must be less than 3.625.
(and so on…)
Continuing this process long enough reveals that the square root of 8 is about 2.828.
My code is messed up somewhere because I keep getting back the same number that I scanned in. This is what I have so far:
Code:#include <stdio.h> #include <math.h> double recursive_square (double n); int main (void) { double num = 0; double result = 0; printf("Enter a number to compute the square root of:\n"); scanf("%lf", &num); result = recursive_square(num); printf("The square root of %lf is about %.3lf \n", num, result); system ("PAUSE"); return 0; } double recursive_square (double n) { double tempval = n/2; do { // If x2 is bigger than n, then we know that the square //root of n must be between 1 and x, if ((tempval*tempval) > n) { tempval /= 2; } //otherwise it's between x and n if (tempval * tempval < n) { tempval += (n - tempval); } } while (((n - tempval) >= .001) || ((tempval - n) >= .001)); return tempval; }