Вопрос

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