0

I wrote a simple c program to find square roots of 2,3,4,5 using newton-raphson iteration technique. This code runs to find and display square root of 2 only. Afterwards it hangs. I could not figure out the problem with this code:

# include<stdio.h>

    float square(float x);
    float absolutevalue(float x);

int main(void)
{
    printf("square root of 2 is %f\n", square(2));
    printf("square root of 3 is %f\n", square(3));
    printf("square root of 4 is %f\n", square(4));
    printf("square root of 5 is %f\n", square(5));

    return 0;
}

float square(float x)
{
    float epsilon = 0.0000001;
    float guess = 1;

    while (absolutevalue(guess*guess - x) >= epsilon)
        guess = ((x/guess) + guess) / 2;

    return guess;
}

float absolutevalue(float x)
{
    if (x < 0)
        x = -x;

    return x;
}
tostao
  • 2,803
  • 4
  • 38
  • 61
user1825355
  • 191
  • 1
  • 3
  • 11

1 Answers1

1

Everything will work fine if you replace float with double everywhere.

piokuc
  • 25,594
  • 11
  • 72
  • 102