### Manual Square Root

For an assignment, I need to write a function that determines the square root of a number, by repeated calculation using the formula:

NG = 0.5(LG+N/LG)

Where NG stands for "Next Guess" and LG stands for "Last Guess."

Thus far, the program just spits out (N/2)+.5. What am I doing wrong?

 ``1234567891011121314151617181920212223`` ``````#include #include using namespace std; long double sqart (long double N, long double LG); void main () { long double N; cout << "Enter a number to find its square root: "; cin >> N; cout << "The square root of " << N << " is: " << sqart (N, 1); getchar (); getchar (); } long double sqart (long double N, long double LG) { long double NG=(LG+(N/LG))/2; while ((NG-LG>0.00001) || (LG-NG>0.00001)) { NG=(LG+(N/LG))/2; LG=NG; } return LG; }``````
Line 20 `LG=NG;`
This guarantees that the test on line 18 `NG-LG>0.00001` will terminate after the first iteration, as NG-LG is zero, which is smaller than the limit of 0.00001

Change the order of the lines, move line 20 so that it is just before line 19 rather than just after.

You could also change line 22 to `return NG;` which will give a more accurate result.

Last edited on
Works as intended now. Thanks for pointing that out!
Topic archived. No new replies allowed.