Possible Duplicate:
Why the result of 1/3=0 in java?
I'm working with java, and part of my code requires a number to be divided by 10. To simplify (and show my question) I just put it into a println:
System.out.println(1/10);
that prints out 0. So, logically, I figured it was casting it to an int, so I tried
System.out.println((double)1/10);
and that printed out the proper 0.1. I don't understand why it automatically cast it into an int the first time though. Where else does it do this? Why?
1 is an int and 10 is an int and when you do int/int you get an int.
If you do 1.0/10 or 1/10.0 or 1.0/10.0 you will get a double as 0.1
IMHO: I think int/int should be a double which you can cast an int if you want integer division. i.e.
I would have
a/b // does double division
(int)(a/b) // does integer division.
instead you have to write
a/b // does integer division
(double) a/b // does double division
It doesn't cast to int, it already is int. int / int is int.
Also note that when you cast to double as in (double)1/10, since the cast operator has higher precedence than division, this is the same as ((double)1)/10, which has the effect of causing the division to happen in double.
If you cast after division as in (double)(1/10), the result will be 0.0 .
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