Java.lang Class

Q1: What will be the output of the program?
public class Example 
{
    public static void main(String [] args) 
    {
        double values[] = {-2.3, -1.0, 0.25, 4};
        int cnt = 0;
        for (int x=0; x < values.length; x++) 
        {
            if (Math.round(values[x] + .5) == Math.ceil(values[x])) 
            {
                ++cnt;
            }
        }
        System.out.println('same results ' + cnt + ' time(s)');
    }
}

A same results 0 time(s)

B same results 2 time(s)

C same results 4 time(s)

D Compilation fails.

ANS:A - same results 0 time(s)

Math.round() adds .5 to the argument then performs a floor(). Since the code adds an additional .5 before round() is called, it's as if we are adding 1 then doing a floor(). The values that start out as integer values will in effect be incremented by 1 on the round() side but not on the ceil() side, and the noninteger values will end up equal.



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.