Casting and Ranges of Variables

AP Computer Science A· difficulty 4/5

double d = 4.7;
int rounded = (int)(d + 0.5);
System.out.println(rounded);

What is printed?

  • A

    6

  • B

    4

  • C

    5

    check_circle
  • D

    5.0

Explanation

Adding 0.5 then truncating performs rounding for positive numbers; 4.7 + 0.5 = 5.2, cast to int gives 5.

Want 10 more like this — adaptive to your weak spots?

Related questions