Calculate square root of a double value with while loop - C Statement

C examples for Statement:while

Description

Calculate square root of a double value with while loop

Demo Code

#include <stdio.h>

double absoluteValue (double x){
    if (x < 0)
        x = -x;/* w  w  w .  ja  v a2s . co m*/
    return x;
}

//Function to compute the square root of a number.

double squareRoot (double x, double epsilon){
    double guess = 1.0;

    while (absoluteValue (guess * guess - x) >= epsilon)
        guess = (x / guess + guess) / 2.0;

    return guess;
}

int main (void)
{
    printf ("squareRoot of 2.0 with epsilon set to 0.1 = %.16f\n", squareRoot (2.0, 0.1));
    printf ("squareRoot of 2.0 with epsilon set to 0.1 = %.16f\n", squareRoot (2.0, 0.01));
    return 0;
}

Result


Related Tutorials