0
Can someone explain this
Can someone explain to me how the output is 15 class Exe { public static void main(String args[]) { float x=9; float y=5; int z= (int)(x/y); switch(z) { case 1: x+=2; case 2: x+=3; default: x+=1; } System.out.println(x); } }
7 Respuestas
+ 6
x/y returns 1.8 (float)
(int) 1.8 returns 1 (taking only integral part)
in switch, falls into the first case.
x = 9 + 2 = 11
no break, so second handling also executed
x = 11 + 3 = 14
still no break, so third handling also executed
x = 14 + 1 = 15
+ 7
Amir01 Thanks for your question.
- - -
Because it is a double instead of a float.
quote:
A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d. It means that it's a single precision floating point literal rather than double precision.
source:
https://stackoverflow.com/questions/13704028/why-is-the-letter-f-used-at-the-end-of-a-float-no/13704077
- - -
Double has more precision and is more accurate, but it also takes up more memory.
Here is a reading about the difference between double and float :
https://javarevisited.blogspot.com/2016/05/difference-between-float-and-double-in-java.html?m=1
+ 4
Remember:
If you donot use break statement at end of each case in switch, then all the cases that comes after matching case will also be executed.
+ 3
For your case,
put 'break;' at the end of case
It will solve your problem like this,
switch(z)
{
case 1: x+=2;
break;
case 2: x+=3;
break;
default: x+=1;
}
The output should be 11.0
Good Luck~
+ 2
nice!
+ 1
Gordon ,you are right!
It makes a question in my mind. I think float variables needs to f at the end,but why above code hasn't any f?
+ 1
Gordon thanks