该函数的目的是使用牛顿-拉夫森方法计算数字的平方根。我在 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;
}
最佳答案
如果您使用 mingw 的 Code::Blocks 版本,请参阅此答案:Conversion specifier of long double in C
mingw ... printf 不支持“long double”类型。
一些更多的支持文档。
http://bytes.com/topic/c/answers/135253-printing-long-double-type-via-printf-mingw-g-3-2-3-a
如果您直接从 float
转到 long double
,您可以尝试仅使用 double
,它的长度是 float 的两倍首先,您可能不需要一直使用 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;
}
关于c - long double 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30548928/