我通过牛顿方法找到平方根的逻辑有什么问题?

时间:2011-04-30 06:11:48

标签: c algorithm math

我写了下面的代码,用牛顿的方法通过逐次近似来找到平方根,但它没有给我正确的答案。有人可以解释一下吗?

#include<stdio.h>
#include<stdlib.h>
#define square(x) x*x
double rootByNewtonApprox(int n);
double improve(double n);
double average(double a,double b);
int goodEnough(double guess);
double guess(int n);
int number;
int main(void)
{

    double root;
    printf("\nEnter the number you want square root of: ");
    scanf("%d",&number);
    if(number<0)
            number = -1* number;
    root = rootByNewtonApprox(number);
    printf("\nThe square root of %d is %lf\n",number,root);
    return 0;
}
double guess(int n)
{
    return n/2;
}
double rootByNewtonApprox(int n)
{
    if(goodEnough(guess(n)))
            return guess(n);
    else
            rootByNewtonApprox(improve(guess(n)));
}

double improve(double guess)
{
    return average(guess,(number/guess));
}
double average(double a,double b)
{
    return ((a+b)/2);
}
int goodEnough(double guess)
{
    if(abs(square(guess) - number) <= 0.001)
            return 1;
    else
            return 0;
}

现在,当我提供n = 2时,它会提供ouput nan,当我提供n = 9时,它会告诉segmentation Fault

2 个答案:

答案 0 :(得分:7)

double guess(int n)
{
    return  n / (double) 2;
}

答案 1 :(得分:3)

您忘了一个return

double rootByNewtonApprox(int n)
{
if(goodEnough(guess(n)))
    return guess(n);
else
    return rootByNewtonApprox(improve(guess(n)));
    ^
}