Using the Math Class

AP Computer Science A· difficulty 4/5

int r = (int)(Math.random() * 10) + 1;

Which range of integer values can r take?

  • A

    0 to 10 inclusive

  • B

    0 to 9 inclusive

  • C

    1 to 11 inclusive

  • D

    1 to 10 inclusive

    check_circle

Explanation

Math.random() returns a double in [0.0, 1.0); multiplying by 10 gives [0.0, 10.0), casting to int gives 0-9, and adding 1 gives 1-10.

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

Related questions