c - modf 功能无法正常工作

标签 c

我正在尝试存储十进制数的所有数字。我决定使用 modf 来实现此目的。我的代码段是;

struct high_precision scan_high(int *j)
{
    int i,a;
    struct high_precision mynum;
    double num1, fracpart, intpart;
    printf("Enter the values> ");
    scanf("%lf", &num1);
    if( num1 < 0 )
        mynum.sign = -1;
    else
        mynum.sign = 1;
    num1 = fabs(num1);
    fracpart = modf(num1, &intpart);
    if ( intpart > 0 && intpart < 10 )
        a = 1;
    while( intpart == 0 ) {
        fracpart *= 10;
        fracpart = modf(fracpart, &intpart);
        a -= 1;
    }
    for(i=0;fracpart > 0 && intpart != 0;i++){
        if( intpart > 0 ){
            mynum.digits[i] = intpart;
        }
        fracpart *= 10;
        fracpart = modf(fracpart, &intpart);
    }
    *j = i;
    mynum.decpt = a;

    return(mynum);
}

但不知怎的,它并没有按照我想要的方式工作。例如;

Enter the values> 0.009876
    0.876000 9.000000
    0.760000 8.000000
    0.600000 7.000000

它必须停在这一行。但是,它仍在继续计数;

1.000000 5.000000
1.000000 9.000000
1.000000 9.000000
1.000000 9.000000
1.000000 9.000000
1.000000 9.000000
0.999998 9.000000
0.999977 9.000000
0.999767 9.000000
0.997669 9.000000
0.976694 9.000000
0.766942 9.000000
0.669420 7.000000
0.694198 6.000000
0.941983 6.000000
0.419827 9.000000
0.198267 4.000000
0.982671 1.000000
0.826707 9.000000
0.267069 8.000000
0.000000 2.000000
0.000000 0.000000

最佳答案

这是因为 float 没有精确存储(例如,不能精确表示)。您可以使用以下示例来说明这一点:

#include <stdio.h>

int main() {
  double x = 0.009876;
  printf("%.20lf\n",x);
  return 0;
}

---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
0.00987599999999999940

> Terminated with exit code 0.

关于c - modf 功能无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6521203/

相关文章:

c - 我听说INC指令不是原子指令。那么,CAS指令如何才能原子化呢?

c - C中的整数指针数组排序

c - Eratosthenes 筛法 C 代码

在 C 中创建延迟

c - 在 Ruby C 扩展中实现链式迭代器

c++ - 从另一个进程在用户模式下回调,没有额外的线程

c - 动态数组中的垃圾值

c - 如何在 C/C++ 中暂停循环

c - preLaunchTask 'helloworld' 以退出代码 1 终止

c - (C) 短整型变量中的位移位/字符放置