Siavash TS
Siavash TS

Reputation: 51

why this C function (newton raphson method for square root of n) doesnt work correctly?

I'm writing code to find square root of numbers using Newton–Raphson method but I can't get the correct output.

When I run this code with any input, I get 0.000003 as result without any errors or alarms.

When I change all double keywords to float it works correctly.

double square(double  n)
{
    register int i;
    double  x = 0.1;
    for (i = 1; i <= 15; i++)
        x -= ((x * x - n) / (2 * x));
    return x;
}

int main()
{
    double  n;
    system("cls");
    printf("enter a num : ");
    scanf("%f",&n);
    printf("\n square is : %f",square(n));
    getch();
    return 0;
}

Upvotes: 0

Views: 361

Answers (2)

ritesh sangani
ritesh sangani

Reputation: 340

This is because the format specifier for double in scanf is "%lf". You have used "%f" which applies only to float. Hence you are getting undefined output.

When I compiled you code I got below compiler warning.

src\main.c:50:13: warning: format '%f' expects argument of type 'float *', but 
argument 2 has type 'double *' [-Wformat=]     
    scanf("%f",&n);
           ~^  ~~
            %lf

Below code works with double.

int main() {
        double n;
        system("cls");
        printf("enter a num : ");
        scanf("%lf", &n);
        printf("\n square is : %f", square(n));
        getch();
        return 0;
}

the result was:

enter a num : 2

 square is : 1.414214

Hope this helps.

Upvotes: 0

pmg
pmg

Reputation: 108978

double n;
scanf("%f",&n);

This is asking scanf to read a float and put it in a space reserved for a double.
Don't do that

Either ask for a float for a space reserved for a float

float n;
if (scanf("%f", &n) != 1) /* error */;

or ask for a double for a space reserved for a double

double n;
if (scanf("%lf", &n) != 1) /* error */;

Upvotes: 4

Related Questions