Created
June 12, 2016 15:33
-
-
Save slavaceornea/c384d382c4f1eda1e9c1676074689177 to your computer and use it in GitHub Desktop.
C code calculates square root using Newton Raphson method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
// Function to get absolute value of the number given by user. | |
float absolute(float num) | |
{ | |
if(num < 0){ | |
num = -num; | |
} | |
return num; | |
} | |
// Function to calculate square root of the number using Newton-Raphson method | |
float square_root(int x) | |
{ | |
const float difference = 0.00001; | |
float guess = 1.0; | |
while(absolute(guess * guess - x) >= difference){ | |
guess = (x/guess + guess)/2.0; | |
} | |
return guess; | |
} | |
int main() | |
{ | |
int number; | |
float root; | |
printf("Enter a number: "); | |
scanf("%i", &number); | |
root = square_root(number); | |
printf("The square root of %i is: %f", number, root); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment