0

# Why 7 / 2 = 3.0?

//I think it's a sololearn mistake double x = 7 / 2; System.out.println(x); //ouput 3.0 https://code.sololearn.com/c6uEc1cWs7VT/?ref=app

11th Aug 2020, 6:36 PM
9 ответов
+ 7
//try running this... public class Program { public static void main(String[] args) { double x = 7.0 / 2; // OR double x = 7 / 2.0; // OR this double x = (double) 7 / 2; // Casting System.out.print(x); } }
11th Aug 2020, 6:38 PM
RKK
+ 7
it's not an error, it's just the way the compiler treats how operation should be done. like in your case, we had double x = 7/2; okay x is double so we'll have our answer in Decimal points, fine! But what about the values are they in double or int? int, right? so the compiler compiles this like 2 | 7 | 3 6 ------------ 1 only 3 is returned to x, however x is double so for the formality, the compiler keeps ".0" at the end of 3. try making one of the values as double like so... double x = 7.0 / 2; or double x = 7 / 2.0;
11th Aug 2020, 6:43 PM
RKK
+ 5
7 and 2 are treated as integers. change 7 to 7.0 or 2 to 2.0 to get a double division.
11th Aug 2020, 6:40 PM
Bahhaⵣ
+ 2
Thanks!
11th Aug 2020, 6:51 PM
+ 2
When you work with variables: int a = 7, b = 2; you would not be able to apply the previous tricks, then you would need to use type casting, if you want the result in doubles: double x = (double) a / b; //x = 3.5
11th Aug 2020, 7:26 PM
Seb TheS
+ 2
7and 3 is type of integer so you need type casting you will cast 7 to 7.0 and 3 to 3.0 it will return 3.5
13th Aug 2020, 5:47 PM
ihsanullah Ihsan
+ 1
Oh thanks!
11th Aug 2020, 6:39 PM