长双的用法

时间:2015-05-30 17:03:36

标签: c casting double long-integer

函数的目的是使用Newton-Raphson方法计算数字的平方根。我在while循环中包含了一个printf例程,因此我可以 root 2的值越来越接近实际值。我最初使用float来定义epsilon但是当我增加epsilon的值时,返回结果的值似乎在一定数量的数字之后被截止。所以我决定将所有变量切换为long double,程序显示负面结果。我该如何解决?

//Function to calculate the absolute value of a number

#include <stdio.h>

long double absoluteValue (long double x)
{
    if (x < 0)
        x = -x;
    return (x);
}

//Function to compute the square root of a number

long double squareRoot (long double x, long double a)
{
    long double guess = 1.0;

    while ( absoluteValue (guess * guess - x) >= a){
        guess = (x / guess + guess) / 2.0;
        printf ("%Lf\n ", guess);
        }

    return guess;
}

    int main (void)
    {
    long double epsilon = 0.0000000000000001;

    printf ("\nsquareRoot (2.0) = %Lf\n\n\n\n", squareRoot (2.0, epsilon));
    printf ("\nsquareRoot (144.0) = %Lf\n\n\n\n", squareRoot (144.0, epsilon));
    printf ("\nsquareRoot (17.5) = %Lf\n", squareRoot (17.5, epsilon));

    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果您使用带有mingw的Code :: Blocks版本,请参阅以下答案:Conversion specifier of long double in C

mingw ... printf does not support the 'long double' type.

更多支持文档。

http://bytes.com/topic/c/answers/135253-printing-long-double-type-via-printf-mingw-g-3-2-3-a

如果您从float直接转到long double,您可以尝试使用double代替,这是浮动开始的两倍,您可能不需要一直到long double

为此您将使用%lf的打印说明符,并且您的循环可能希望看起来像这样,以防止基于您的epsilon的无限循环:

double squareRoot (    double x,     double a)
{
    double nextGuess = 1.0;
    double lastGuess = 0.0;

    while ( absoluteValue (nextGuess * nextGuess - x) >= a && nextGuess != lastGuess){
        lastGuess = nextGuess;
        nextGuess = (x / lastGuess + lastGuess) / 2.0;
        printf ("%lf\n ", nextGuess);
        }

    return nextGuess;
}