| Author |
why this output?
|
Vishy Karl
Ranch Hand
Joined: Sep 08, 2003
Posts: 116
|
|
Hi All, Why is the following o/p correct for fol. statement. ? System.out.print((1 - 1 / 3 * 3 ==0)+" "); //1 System.out.print((1 - 1.0f / 3.0f * 3.0f==0)+" "); //2 System.out.print((1 - 1.0f / 3.0f * 3.0d==0)+" "); //3 System.out.print((1 - 1.0d / 3.0d * 3.0d==0)+" "); //4 Correct Ans is A: false true false true Thanks in advance,
|
"The man who can drive himself further once the effort gets painful is the man who will win." <br />Roger Bannister
|
 |
Jessica Sant
Sheriff
Joined: Oct 17, 2001
Posts: 4313
|
|
The 1st one is false because those numbers are integers. So the decimal are stripped off and you're left with just the integer when you do division. So.... the problem breaks down like this 1 - ( 1/3 ) * 3 == 0 1 - ( 0 ) * 3 == 0 1 - 0 == 0 1 == 0 false #'s 2,3,4 behave as you'd expected because the numbers are floating points. so 1.0/3.0 == 0.333333
|
- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
|
 |
dennis zined
Ranch Hand
Joined: Mar 07, 2003
Posts: 330
|
|
|
Hello. Why is the third false?
|
SCJP 1.4<br />SCWCD 1.4
|
 |
Lakshmi Saradha
Ranch Hand
Joined: Oct 21, 2003
Posts: 170
|
|
Hi, I think the expression involving multiplication and division makes the difference. class a { public static void main(String args[]) { //System.out.print((1-1.0d / 3.0d * 3.0d)==0); //System.out.print((1 - 1.0f / 3.0f * 3.0f==0)+" "); //System.out.print((1 - 1.0f / 3.0f * 3.0d==0)+" "); System.out.println( "float double"+1.0f / 3.0f * 3.0d); //line 1 System.out.println( "double only"+1.0d / 3.0d * 3.0d); //line 2 } } Line1 gives an output of 1.0000000298023224 Line 2 gievs an output of 1.0. Why is this happening? I was thinking that both the expression would evaluate to double .
|
Thanks,<br />Lakshmi.
|
 |
Sumitro Palit
Ranch Hand
Joined: Dec 13, 2003
Posts: 37
|
|
Lakshmi, System.out.println(1.0f / 3.0f * 3.0d); is the same as System.out.println((1.0f / 3.0f) * 3.0d); The result of 1.0f/3.0f is a float, which is promoted to a double and then added to 3.0d Try this code and the difference will become apparent: System.out.println((1.0f / 3.0f)); System.out.println((1.0d / 3.0d)); - Ortimus
|
 |
 |
|
|
subject: why this output?
|
|
|