Why 1.2 * 30 = 35?

Why is this:

int main(void)
{
    short w = 30;
    return  1.2 * w;
}

return 35?

+3
source share
7 answers

If you want a more suitable result, try the following:

return 12*w/10
+14
source

1.2 * w 36.0. It has a double type, meaning that it is not represented accurately.

It will probably turn out to be a little smaller 36, maybe 35.99999, therefore, when you return it, the fractional part is discarded and only the integer part is returned. How do you get 35.


P.S. . . , , , .

: if (value == 36.0) { /* ... */ }

: if (abs (value - 36.0) < 0.0001) { /* ... */ }

+12

. 1.2 1,2, 36.

+3

- : 1.2 - 1.1999999

+3

, round() , , .

#include <math.h>
...
return (int)round(some_real_value);
+3

Do not expect an absolutely accurate result in floating point operations. The result of the multiplication can be, for example, 35,9999, which is rounded to 35.

+1
source

short w = 30; return 1.2 * w;

In the original expression, the first sort value is the type cast in double, because 1.2 is a double type, so it will multiply 1.2 * 30.000000 and the result will be about 35.999999, and the return type is int function, so the decimal part is truncated and returned only 35.

0
source

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


All Articles