About Question com.enthuware.ets.scjp.v6.2.227 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Andrei Test

About Question com.enthuware.ets.scjp.v6.2.227 :

Post by Andrei Test »

Quote from the explanation :
Note that. actually 1/3 is .33333333..... but it shows f as .33...4, So f*3 is 1.00...X (a little more than one.) but it is too precise to be represented by a float so we get 1.0. So, finally the code prints true. Had f been a double, it would have printed false.

So why the expected result is false ?
I checked it in the code, it prints true and I selected "true" as a correct response, but the application says that I am wrong.

Online
admin
Site Admin
Posts: 10384
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question com.enthuware.ets.scjp.v6.2.227 :

Post by admin »

That's because the question says it will print false. You need to read the question very carefully.

Andrei Test

Re: About Question com.enthuware.ets.scjp.v6.2.227 :

Post by Andrei Test »

Another tricky question...
Thank you very much ;)

Bartosz Jagodziński

Re: About Question com.enthuware.ets.scjp.v6.2.227 :

Post by Bartosz Jagodziński »

You state in the explanation that:
Had f been a double, it would have printed false.
Which is confiusing because only if you modify the code like this:

Code: Select all

 double f = 1.0f/3.0f;
	    System.out.println(  (f * 3.0f) == 1.0f  );
it prints false...

Any other modifications end up printing true. Please clarify the explanation.

Cheers from Poland!

Online
admin
Site Admin
Posts: 10384
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question com.enthuware.ets.scjp.v6.2.227 :

Post by admin »

Hello,

The problem is with double f = 1.0f/3.0f;

For f to get the high resolution double value, the expression on the right hand side must evaluate to a high resolution double value. However, when you do 1.0f/3.0f, you are forcing the RHS to perform float division and then promote the resulting float (which has already lost the high resolution), to double. So the variable f only gets a less precise double value.

For the RHS to perform double computation, at least one operand should be a double. So 1.0/3.0f or 1.0f/3.0 will print true.

HTH,
Paul.

Post Reply

Who is online

Users browsing this forum: No registered users and 10 guests