学习C几天,想写一个代码,通过牛顿方法找到数字的平方根。
#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));
}
有什么错误?错误:进程返回-1073741819(0xC0000005)执行时间:2.371秒
你应该将double
传递给函数,相反,在main中,你传递一个浮点数。
只需将float a;
改为double a;
另外,在main中,你必须写scanf("%lf",&a);
而不是scanf("%lf",a);
。这是你计算通过程序的正确数字的唯一方法。