Given the following, 1. public class Example { 2. public static void main(String [] args) { 3. double values[] = {-2.3, -1.0, 0.25, 4}; 4. int cnt = 0; 5. for (int x=0; x < values.length; x++) { 6. if (Math.round(values[x] + .5) == Math.ceil(values[x])) { 7. ++cnt; 8. } 9. } 10. System.out.println("same results " + cnt + " time(s)"); 11. } 12. } what is the result? A. same results 0 time(s) B. same results 2 time(s) C. same results 4 time(s) D. Compilation fails. E. An exception is thrown at runtime.

its anser is "B"

but don't understand why... i am not able to understand its explaination... kindly clear the doubt...

Originally posted by amit taneja: hi in chapter 6...

in one question...

Given the following, 1. public class Example { 2. public static void main(String [] args) { 3. double values[] = {-2.3, -1.0, 0.25, 4}; 4. int cnt = 0; 5. for (int x=0; x < values.length; x++) { 6. if (Math.round(values[x] + .5) == Math.ceil(values[x])) { 7. ++cnt; 8. } 9. } 10. System.out.println("same results " + cnt + " time(s)"); 11. } 12. } what is the result? A. same results 0 time(s) B. same results 2 time(s) C. same results 4 time(s) D. Compilation fails. E. An exception is thrown at runtime.

its anser is "B"

but don't understand why... i am not able to understand its explaination... kindly clear the doubt...

thanx

The logic is as follows:

-2.3 and 0.25 are the correct answers.

For -2.3:

(-2.3 + .5) == -1.7 -1.7 Rounded == -2.0

-2.3 Ceiled == -2

Therefore -2.0 == 2

For 0.25:

(0.25 + .5) == 0.75 0.75 Rounded == 1.0

0.25 Ceiled == 1

Therefore 1.0 == 1

-1.0 is not correct because:

(-1.0 + .5) == -.5 -.5 Rounded == 0

-1.0 Ceiled == -1.0

Therefore 0 != -1.0

4 Is incorrect because:

(4 + .5) == 4.5 4.5 Rounded == 5

4 Ceiled == 4

Therefore 4 != 5

Marco Tedone<br />SCJP1.4,SCJP5,SCBCD,SCWCD

Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228

posted

0

Therefore -2.0 == 2

It should be -2.0 == -2.0

alzamabar
Ranch Hand

Joined: Jul 24, 2002
Posts: 379

posted

0

Originally posted by Srinivasa Raghavan:

It should be -2.0 == -2.0

No, it should be -2.0 == 2

From Java Language Specification (chapter 5.6.2):

If either operand is of type double, the other is converted to double.

Therefore 2 is promoted to be 2.0 and the two results are equal.