i writed double x = (17/100) * 888; return x . as a result 0.0 .
why even if only x = 17/100 , will be as result 0.0 ?
i already finished this task, but I am very interested in why this is so.
user 2710
Level 4
why is 17/100 not 0.17? result 0.0?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
3 September 2021, 21:31
Unless specified, or if the number is a decimal number, Java defaults all numbers to ints and type int can not store/carry a decimal value. If you want to have a decimal result you need to convert one of the numbers to a decimal value so that the result carries a decimal. So all of these are acceptable:
17.0/100
17/100.0
(double)17/100
17/(double100)
0
Gellert Varga
3 September 2021, 21:30
The Java Virtual Machine (JVM) always interprets numbers in code as int by default.
17 is an int, not a double.
100 is an int, not a double.
Consequently, 17/100 will also be an int, not a double.
Although when we humans look at 17/100, it means 0.17 to us, but we only need to look at the int part of that 0.17 now, and that is zero.
99/100 also equals zero.
100/100 is 1.
int x = 1/2; // x==0
double y = 1/2; // y==0.0
The second line first does the division, which is 0, and then puts this int into the variable of type double, so 0 is converted to double, which is 0.0
If you want to get exactly 0.17, you have to convert one of the factors to double, for example by tricks like this:
double x = (17*1.0) / 100;
double y = 17 / 100.0;
double z = 17 / (100+ 0.0);
+1