-4

I am trying to make a program in C to find the approximate square root of a number using the formula NG = 0.5( LG + N/ LG). So far i have:

#include <stdio.h> 
#include <math.h> 
int main(){
    double n;
    double LG=1;
    double NG;
    printf("Enter number");
    scanf_s("%lf",&n);
    do{
        NG=(.5*(LG+n/LG));
        LG=NG;
    }while((NG*NG-n)<.005);
    printf("The root is %lf",NG);
}

This structure works fine in java, but the loop doesn't seem to be executing in C.

Thanks for any advice.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
user3221816
  • 135
  • 2
  • 2
  • 10
  • 3
    Shouldn't the statement inside the loop be `NG=(.5*(LG+n/LG));`? – MBlanc Feb 18 '14 at 15:30
  • 1
    Have you put it in a debugger, set a breakpoint and stepped through the code? If not, why not? – abelenky Feb 18 '14 at 15:32
  • It should, I meant 0.5, that was a typo, sorry. – user3221816 Feb 18 '14 at 15:35
  • 2
    Find a case where you get the wrong answer. Write down **on a piece of paper** everything you believe your program *should* do with that number. Now step through the code in the debugger and check off every time your program does something you expect it to do. The first thing it does that you don't expect it to do, **that's where the bug is**. – Eric Lippert Feb 18 '14 at 15:49
  • 2
    This question appears to be off-topic because StackOverflow is not a service for debugging your buggy code. – Eric Lippert Feb 18 '14 at 15:49
  • 1
    @Yu Hao The `printf()` format specifier for `double` may use either `"%f"` or `"%lf"`. `l` has no effect on a following `a, A, e, E, f, F, g, or G` conversion specifier. – chux - Reinstate Monica Feb 18 '14 at 16:24

1 Answers1

3

You do not want to loop while NG*NG-n is less than .005. You want to loop while NG*NG is farther from n than desired.

The distance between NG*NG and n is fabs(NG*NG - n).

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Oh oops, you're right, thanks. It is returning a value, now, but it is an incorrect value. For instance entering 49 returns 25 and entering 36 returns 18.5. – user3221816 Feb 18 '14 at 15:47
  • @user3221816 Judgment is probably inverse. use `}while(fabs(NG*NG-n)>.005);` – BLUEPIXY Feb 18 '14 at 15:55
  • @user3221816: Not using `fabs` is not the only error. Think about the **while** part. You are looping **while** something is true. Loop **while** the number is too far, not while the number is too close. – Eric Postpischil Feb 18 '14 at 15:56