+ 3

why xy = 0.0 ?

public class Test{ public static void main(String[] args){ int x = 1, y = 2; double xy = x / y; System.out.println(xy); } }

17th Oct 2017, 4:53 PM
YuHai
YuHai - avatar
6 ответов
+ 3
Because you're dividing integer by integer and after that you are storing the result into xy (1/2=0 ==> xy=0=0.0)(declaring the variable xy doesn't change the data types of x and y). to fix that, you should change x or y to double.
17th Oct 2017, 4:57 PM
WildGeese
WildGeese - avatar
+ 3
Fix: double xy = (double) x / y;
17th Oct 2017, 5:56 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
So,if i devide an integer by an integer,the answer will also be integer?
17th Oct 2017, 5:07 PM
YuHai
YuHai - avatar
+ 1
yes. in the code above you have stored an integer result to a double variable.
17th Oct 2017, 5:08 PM
WildGeese
WildGeese - avatar
+ 1
However, if you divide integer by double or double by double the result will be double.
17th Oct 2017, 5:09 PM
WildGeese
WildGeese - avatar
0
thank you,Nabeeh.
22nd Oct 2017, 6:21 AM
YuHai
YuHai - avatar