문제

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.

도움이 되었습니까?

해결책

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).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top