-1

这是我的代码:

#include <stdio.h>
static long double   ft_ldmod(long double x, long double mod)
{
    long double res;
    long double round;
    res = x / mod;
    round = 0.0L;
    while (res >= 1.0L || res <= -1.0L)
    {
        round += (res < 0.0L) ? -1.0L : 1.0L;
        res += (res < 0.0L) ? 1.0L : -1.0L;
    }
    return ((x / mod - round) * mod);
}
int  main(void)
{
    long double x;
    long double r;
    x = 0.0000042L;
    r = ft_ldmod(x, 1.0L);
    while (r != 0.0L)  // <-- I have an infinite loop here
    {
        x *= 10.0L;
        r = ft_ldmod(x, 1.0L);
    }
    printf("%Lf", x);
    return (0);
}

似乎有什么问题,但无法弄清楚。主函数中的while循环循环并且不中断。即使条件是错误的,它也会消失...欢迎帮助,谢谢。

4

1 回答 1

0

之后x = 0.0000042L;, 的值x取决于long double您的 C 实现使用的格式。它可能是 4.2000000000000000001936105559186517000025418155928491614758968353271484375•10 -6。因此,其十进制表示中的数字比问题中的代码预期的要多。随着数字反复乘以 10,它会变大。

随着它变得越来越大,达到数百万和数十亿,ft_ldmod它变得越来越慢,因为它round通过按个数来找到所需的值。

再者,即使ft_ldmod给了足够的时间,x最终round也会变得如此之大,以至于加一个round也没有效果。也就是说,表示roundin的大值long double将需要一个大到用于表示roundin的最低位long double表示值 2 的指数。

从本质上讲,该程序作为一种查找x. 此外,该语句x *= 10.0L;会产生舍入误差,因为将一个数字乘以 10 的精确数学结果通常不能在 中精确表示long double,因此它会四舍五入到最接近的可表示值。(这类似于十进制乘以 11。从 1 开始,我们得到 11、121、1331、14641 等。位数增加。类似地,二进制乘以 10 会增加有效位数。)

于 2018-12-16T15:18:51.430 回答