+ 2
Why System.out.println(450/100) gives me 4 as a result and not 4.5?
I'm new to Java but that strange behavior makes my attempts to learn Java miserable.
4 Answers
+ 8
In Java and some other programming languages, dividing two whole numbers gives you a whole number result.
In this case, the answer is 4.5, but since the result must be a whole number, the 0.5 is truncated and you get 4.
If you want a double result, cast one of the numbers to double, or write one as a double. Ex: 450 / 100.0
+ 6
Reply to Emo:
What about when I use variable
Same...As Tamra's Ex...
double var = 450.0/100.0
or
float var = 450.0/100.0
or
auto var = 450.0/100 //This is c++
or
Object var = 450.0/100
+ 1
//you can try
System.out.println((double)450/100); // 4.5
//As int can not have decimal values
0
What about when I use variables?