Created
December 14, 2014 08:46
-
-
Save bitnenfer/ac57bd704340a4ae75b8 to your computer and use it in GitHub Desktop.
Square Root
This file contains hidden or 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> | |
#include <stdlib.h> | |
#include <math.h> | |
#define PRECISION 0.00001f | |
double SQRT (double input); | |
double SQRT_PREC (const double *input, double precision); | |
int main (int argc, char **argv) { | |
double value; | |
int cvalue; | |
while (1) { | |
cvalue = 0; | |
printf("Input value to calculate square root:\n"); | |
scanf("%lf", &value); | |
printf("Square root of %lf is %lf\n", value, SQRT(value)); | |
printf("Do you want to try another value? [Y / N] "); | |
while (cvalue != 89 && cvalue != 78 && | |
cvalue != 121 && cvalue != 110) { | |
getchar(); | |
cvalue = getchar(); | |
} | |
if (cvalue == 78 || cvalue == 110) break; | |
} | |
return 0; | |
} | |
double SQRT (double input) { | |
return SQRT_PREC(&input, PRECISION); | |
} | |
double SQRT_PREC (const double *input, double precision) { | |
double greater, middle, lower, test; | |
greater = *input; | |
lower = greater / 2; | |
middle = (lower + greater) / 2; | |
test = middle * middle; | |
while (fabs(*input - test) >= precision) { | |
if (test > *input) { | |
greater = middle; | |
lower = greater / 2; | |
} else { | |
lower = middle; | |
} | |
middle = (lower + greater) / 2; | |
test = middle * middle; | |
} | |
return middle; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment