小数点后数字的计数器(双精度)

Сounter of digits after decimal point (double)

请帮忙解决这个问题。我需要计算小数点后的位数。但是当 f 应该是 0 它变成 1i 变成 2(但应该是 3)。 代码之后,控制台的输出

#include <math.h>
#include <stdio.h>       

int main()
{
  double i;
  double f;
  int count = 0;
  double eps = 10.123;

  while(f!=0){
  f = modf(eps, &i);
  printf("%f \n%f\n", i, f);
  count = count + 1;
  i=0;
  eps=f*10;
  printf("%f\n\n", eps);
  }
  printf("Count = %d", count);

    return 0;
}

10.000000 0.123000 1.230000

1.000000 0.230000 2.300000

2.000000 0.300000 3.000000

2.000000 1.000000 10.000000

9.000000 1.000000 10.000000

9.000000 1.000000 10.000000

9.000000 1.000000 10.000000

9.000000 1.000000 10.000000

9.000000 1.000000 9.999999

9.000000 0.999999 9.999993

9.000000 0.999993 9.999933

9.000000 0.999933 9.999332

9.000000 0.999332 9.993321

9.000000 0.993321 9.933209

9.000000 0.933209 9.332090

9.000000 0.332090 3.320898

3.000000 0.320898 3.208983

3.000000 0.208983 2.089828

2.000000 0.089828 0.898284

0.000000 0.898284 8.982839

8.000000 0.982839 9.828386

9.000000 0.828386 8.283855

8.000000 0.283855 2.838551

2.000000 0.838551 8.385506

8.000000 0.385506 3.855058

3.000000 0.855058 8.550583

8.000000 0.550583 5.505825

5.000000 0.505825 5.058253

5.000000 0.058253 0.582528

0.000000 0.582528 5.825281

5.000000 0.825281 8.252811

8.000000 0.252811 2.528114

2.000000 0.528114 5.281143

5.000000 0.281143 2.811432

2.000000 0.811432 8.114319

8.000000 0.114319 1.143188

1.000000 0.143188 1.431885

1.000000 0.431885 4.318848

4.000000 0.318848 3.188477

3.000000 0.188477 1.884766

1.000000 0.884766 8.847656

8.000000 0.847656 8.476562

8.000000 0.476562 4.765625

4.000000 0.765625 7.656250

7.000000 0.656250 6.562500

6.000000 0.562500 5.625000

5.000000 0.625000 6.250000

6.000000 0.250000 2.500000

2.000000 0.500000 5.000000

5.000000 0.000000 0.000000

计数 = 50

仅仅因为您将 10.123 分配给变量并不意味着 正是 那里存储的内容。

浮点表示只是近似值(尽管它们确实具有非常高的精度)

10.123无法精确存储,二进制近似为10.1229999999...,如这段代码所示

#include <stdio.h>

int main(void) {
    double x = 10.123;
    
    printf("%3.3f is stored as %3.20f\n", x, x);
    return 0;
}

输出:

10.123 is stored as 10.12299999999999933209

换句话说,您的代码运行正常。