+ 5

Why does this produce a result of 1?

class Program { public static void main(String[] args) { double a = 12/7; System.out.println(a); } } I still don't get it. I used the double data type. Result: 1

30th Jan 2018, 12:14 AM
Unidentified
Unidentified - avatar
6 Respuestas
+ 20
Integer/Integer returns an Integer in java //it works like greatest integer function for natural numbers ie 12/7 = 1.something =1 //bcz Integer/Integer is Integer in java
28th Jan 2018, 4:19 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 14
@unidentified , double a=12/7 , means double a=1.0 bcz 12&7 are integers //to avoid that u can write double a=(double)12/7; or double a=12.0/7.0;
30th Jan 2018, 3:33 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
How do I get it to produce the correct result?
29th Jan 2018, 9:32 PM
Unidentified
Unidentified - avatar
+ 3
the double output produces 1.0, but the compiler makes assumptions based on input too, and since your first value (12) is int, the result is an int. To enforce double, you need to define the first value as double too: double b = 12; double a = b / 7;
30th Jan 2018, 12:25 AM
Roddy Mackenzie
Roddy Mackenzie - avatar
+ 3
Just tried something and there is a way to enforce double without declaring new variables. Instead of 12 / 7, do 12.0 / 7.0, this will return 1.7...
30th Jan 2018, 12:38 AM
Jacob Pembleton
Jacob Pembleton - avatar