长双的用法
函数的目的是用牛顿 - 拉夫森法计算一个数的平方根。 我在while循环中包含了printf例程,所以我可以看到 root 2的值越来越接近实际值。 我最初使用float来定义epsilon,但是当我增加了epsilon的值时,返回结果的值似乎在一定数量的数字后被截断。 所以我决定把所有的变量都切换成长整倍数,程序显示的是负值结果。 我如何解决它?
//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 ("%Lfn ", guess);
}
return guess;
}
int main (void)
{
long double epsilon = 0.0000000000000001;
printf ("nsquareRoot (2.0) = %Lfnnnn", squareRoot (2.0, epsilon));
printf ("nsquareRoot (144.0) = %Lfnnnn", squareRoot (144.0, epsilon));
printf ("nsquareRoot (17.5) = %Lfn", squareRoot (17.5, epsilon));
return 0;
}
如果你正在使用mingw的Code :: Blocks版本,请看这个答案:C中long double的转换说明符
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 ("%lfn ", nextGuess);
}
return nextGuess;
}
链接地址: http://www.djcxy.com/p/85735.html