+ 1

Why the ans is 2.0 not 2.5. Please explain me the logic behind the output.

Question: what is the output int a=5; int b=2; double result=(double)(5/2); System.out.print(result); Ans is 2.0 Explain the logic behind it https://code.sololearn.com/coNpCo4Mejwu/?ref=app https://code.sololearn.com/coNpCo4Mejwu/?ref=app

13th Mar 2019, 4:30 AM
Ayush Pandey
Ayush Pandey - avatar
6 odpowiedzi
+ 3
Ayush Pandey Chriptus actually explained it in his earlier reply. When you do 5/2 , integer division takes place. 5 is divided by 2 to give 2 (with remainder of 1). The result of the division is 2. The resulting value is the casted to double, which is 2.0
13th Mar 2019, 2:55 PM
Hatsy Rei
Hatsy Rei - avatar
+ 6
If you look at the operator precedence table, http://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html Unary type cast has higher precedence compared to division operator. (double)5/2 should be interpreted as ((double)5)/2, which should give you 2.5. I compiled your code using javac 1.8.0_191, and received result of 2.5. Can you show us the full code which gives you 2.0, or is this a challenge question? Are you sure you memorized the challenge details correctly?
13th Mar 2019, 4:43 AM
Fermi
Fermi - avatar
+ 2
Chriptus13 sir I dont need alternate option I wanna know logic behind it
13th Mar 2019, 1:33 PM
Ayush Pandey
Ayush Pandey - avatar
+ 1
Fermi and Chriptus13 Now I have corrected the question sorry for the inconvinence.Please explain me.
13th Mar 2019, 8:57 AM
Ayush Pandey
Ayush Pandey - avatar
+ 1
My answer applies to this aswell if you want to obtain 2.5 you need to cast one of them to double first, eg: // double result = ((double)5)/2; Or, you can also multiply one by 1.0 // double result = (double)(5*1.0/2)
13th Mar 2019, 9:02 AM
Chriptus13
Chriptus13 - avatar
0
Since 5 and 2 are ints the division will give u 2 without the rest and therefore when casting to double you get 2.0
13th Mar 2019, 8:48 AM
Chriptus13
Chriptus13 - avatar