Type Casting Math.random?

前端 未结 2 1362
野趣味
野趣味 2021-01-20 01:26

Had a look around the questions on this site and could not quite find the answer I was looking for about type casting the Math.random() method from double to in

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-20 02:05

    Math.random() returns a number from 0 to 1. You want to cast the result of (Math.random()*10) to int, not the number you get from Math.random itself. Numbers get rounded down. Therefore, for example, 0.3, which you can get from Math.random, gets rounded to 0. Again, you want to round the result of 0.3 times 10, which is 3. The parenthesis is important.

提交回复
热议问题