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
Adrián
Adrián - avatar
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
minirkk
minirkk - avatar
+ 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
minirkk
minirkk - avatar
+ 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ⵣ
Bahhaⵣ - avatar
+ 2
Thanks!
11th Aug 2020, 6:51 PM
Adrián
Adrián - avatar
+ 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
Seb TheS - avatar
+ 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
ihsanullah Ihsan - avatar
+ 1
Oh thanks!
11th Aug 2020, 6:39 PM
Adrián
Adrián - avatar
+ 1
The java compiler sees your 7 and 2 as integers and it only converts them to double types after they have been calculated as integers. This means 7/2 will give 3. And then the fact that you are assigning the answer to a double variable doesn't actually happen until the whole division. Which means in double x= 7/2 The value of x now is actually 3.0 and not 3.5 as you would have expected
13th Aug 2020, 4:43 PM
Theedon
Theedon - avatar
0
Thank you
11th Aug 2020, 10:58 PM
Adrián
Adrián - avatar