0

ニュートンラフソン反復法を使用して 2,3,4,5 の平方根を見つける簡単な C プログラムを作成しました。このコードは、2 の平方根のみを検索して表示するために実行されます。その後、ハングします。このコードの問題を理解できませんでした:

# include<stdio.h>

    float square(float x);
    float absolutevalue(float x);

int main(void)
{
    printf("square root of 2 is %f\n", square(2));
    printf("square root of 3 is %f\n", square(3));
    printf("square root of 4 is %f\n", square(4));
    printf("square root of 5 is %f\n", square(5));

    return 0;
}

float square(float x)
{
    float epsilon = 0.0000001;
    float guess = 1;

    while (absolutevalue(guess*guess - x) >= epsilon)
        guess = ((x/guess) + guess) / 2;

    return guess;
}

float absolutevalue(float x)
{
    if (x < 0)
        x = -x;

    return x;
}
4

1 に答える 1

1

どこでも置き換えるfloatと、すべてが正常に機能します。double

于 2012-12-21T14:23:34.853 に答える