Why does not it work! Int ()?

Why does this statement fail?

import std.conv; void main() { auto y = 0.6, delta=0.1; auto r = to!int(y/delta); assert(r == 6); } 

r value should be 6, and yet it is 5, why?

+5
source share
2 answers

This is probably because 0.6 cannot be represented simply in floating point numbers. You write 0.6, but this is not exactly what you get - you get something like 0.599999999. When you divide this by 0.1, you get something like 5.99999999, which converts to the integer 5 (rounding down).

Examples in other languages:

C #: Why (double) 0.6f> (Double) (6 / 10f)?

Java: Can someone please explain to me that in java why 0.6 is <0.6f but 0.7is> = 0.7f

+5
source

Computers represent floating point numbers in binary format. Decimal numbers 0.6 and 0.1 do not have an exact binary representation, and the number of bits used to represent them is, of course. The result would be a truncation, the effect of which is observed during division. The result of this separation is not exactly 6.00000000, but perhaps 5.99999999, which then truncates to 5.

+4
source

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


All Articles