+ 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
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
+ 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;
+ 5
How do I get it to produce the correct result?
+ 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;
+ 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...