我自己的sqrt()函数哪里出错了?
Where are the mistakes in my own sqrt() function?
学了几天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
您应该将 double
传递给该函数,而在 main 中,您传递的是一个浮点数。
只需将 float a;
更改为 double a;
此外,在 main 中,您必须写 scanf("%lf",&a);
而不是 scanf("%lf",a);
。这是计算通过程序的正确数字的唯一方法。
学了几天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
您应该将 double
传递给该函数,而在 main 中,您传递的是一个浮点数。
只需将 float a;
更改为 double a;
此外,在 main 中,您必须写 scanf("%lf",&a);
而不是 scanf("%lf",a);
。这是计算通过程序的正确数字的唯一方法。