Learning C for a couple of days, wanted to write a code to find the square root of a number by Newton's method.
#include <stdio.h>
#include <stdlib.h>
int truncate (double num) //rounds float to integer
{
if (num < 0) {
return (num + 0.5);
}
else {
return (num - 0.5);
}
}
double sqr(double num){ //square function
return num * num;
}
double sqrt(double number) { //root function
double guess, quotient, average;
guess = 1.0;
do {
quotient = number / guess;
printf("%f\t", quotient);
average = (guess + quotient) / 2.0;
printf("%f\n", average);
guess = average;
} while ((abs(number - sqr(guess))) > 0.001);
return guess;
}
int main(){
float a;
scanf("%f", a);
printf("%.2f", sqrt(a));
}
What are the mistakes? Error: Process returned -1073741819 (0xC0000005) execution time : 2.371 s
You should pass a double
to the function, instead, in main, you're passing a float.
just change float a;
to double a;
Also, in main, you have to write scanf("%lf",&a);
instead of scanf("%lf",a);
. That's the only way you'll calculate on the right number you pass your program.
User contributions licensed under CC BY-SA 3.0