Number of digits after `.` in floating point numbers?

This is one interview question. How do you calculate the number of digits after .in a floating point number.

eg. if 3.554 output = 3 is given

for 43.000 output = 0. My code snippet is here

double no =3.44;
int count =0;
while(no!=((int)no))
{
    count++;
    no=no*10;
}
printf("%d",count);

There are some numbers that cannot be specified by type float. for example, there is no type 73.487in b float, the number indicated floatin c is << 26> to approximate it.

Now, how to solve it, since it is going in an endless loop.

Note. In the IEEE 754 specifications, a 32-bit float is divided into 24 + 7 + 1 bits. 7 bits indicate the mantissa.

+2
source share
7 answers

, , , . , ( ) .

, , , , , 2 3.44.

, , 3.44 2 - 3.44 * 10.0 * 10.0 344.0. , , 3.43 ( ).

1.0/3.0, . printf , no 33333333333333324.0 17 - , int ( , ), int undefined.

10 . , .

3.44 double, , ( , ), 3.439999999999999946709294817992486059665679931640625, 51 . , 3.439999999999999946709294817992486059665679931640625. 3.44 3.439999999999999946709294817992486059665679931640625 , - C- , 2 51 ( 50, 3.43999999999999994670929481799248605966567993164062, ...).

, , " " 3.44, - 3.439999999999999946709294817992486059665679931640625.

, , , , (, ), - , .

, , , .

+2

, , , -, , :

int digits_after_decimal_point(double x)
{
    int i;
    for (i=0; x!=rint(x); x+=x, i++);
    return i;
}
+5

, sprintf , ( float).

, , .

+2

:

, .

, : , - . :

. . . . ACM SIGPLAN 1996 , 1996 .

http://www.cs.indiana.edu/~dyb/pubs/FP-Printing-PLDI96.pdf

. Smalltalk.

+2

. , . , , 0 9 . , .

, 16-17 , 73.486999999999995 17 - 2 ( 2 int-) . , , , .

0

, 10, , 10. , .

, , , PLDI 1990 2003 Retrospective, , .

-1

: . 3.554 output = 3 43.000 output = 0

: , 0.33345. , - 0.333459999... 125. , , 0.33345 - , .

, , . < br/ " >
int digits (double v) {
     int d = 0; (d < 50) {
        string t = DoubleToString (v, d); double vt = StrToDouble (t);
        if (MathAbs (v-vt) < 1e-15) break;
        ++ ;
     }
     return d;
  }
  double v = 0,33345; PrintFormat ( "v =% g, d =% i", v, (v));//v = 0.33345, d = 5
         v = 0,01; PrintFormat ( "v =% g, d =% i", v, (v));//v = 0.01, d = 2
         v = 0,00001; PrintFormat ( "v =% g, d =% i", v, (v));//v = 1e-05, d = 5
         v = 5 * 0,00001; PrintFormat ( "v =% g, d =% i", v, (v));//v = 5e-05, d = 5
         v = 5 * 0,1 * 0,1 * 0,1; PrintFormat ( "v =% g, d =% i", v, (v));//v = 0,005, d = 3
         v = 0,05; PrintFormat ( "v =% g, d =% i", v, (v));//v = 0,05, d = 2
         v = 0,25; PrintFormat ( "v =% g, d =% i", v, (v));//v = 0.25, d = 2
         v = 1/3.; PrintFormat ( "v =% g, d =% i", v, (v));//v = 0.333333, d = 15

-one
source

Source: https://habr.com/ru/post/1502944/


All Articles