学习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 s
答案 0 :(得分:0)
您应该将double
传递给该函数,相反,主要是要传递一个浮点数。
只需将float a;
更改为double a;
此外,总的来说,您必须编写scanf("%lf",&a);
而不是scanf("%lf",a);
。这是唯一根据传递程序的正确数字进行计算的方法。