If I have an int
, convert it to a double
, then convert the double
back to an int
, am I guaranteed to get the same value back that I started with? In other words, given this function:
int passThroughDouble(int input) { double d = input; return d; }
Am I guaranteed that passThroughDouble(x) == x
for all int
s x
?
Short answer is "no" - the range of values an int can represent and that a double can represent are implementation defined - but a double certainly cannot support every integral value in the range it can represent.
The %d format specifier expects an int argument, but you're passing a double . Using the wrong format specifier invokes undefined behavior. To print a double , use %f .
In Java, integer addition and double addition use different hardware. Even though they may seem the same to you, they are actually quite different to the computer. The computer wants to either add two int values or two double values. Java's solution (as in many other languages) is type promotion.
You can safely assign a floating point variable to an integer variable, the compiler will just truncate (not round) the value. At most the compiler might give you a warning, especially if assigning from e.g. a double or bigger type.
No it isn't. The standard says nothing about the relative sizes of int
and double
.
If int
is a 64-bit integer and double
is the standard IEEE double-precision, then it will already fail for numbers bigger than 2^53
.
That said, int
is still 32-bit on the majority of environments today. So it will still hold in many cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With