math.random always give 0 result

前端 未结 8 804
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 16:40

I am using Ubuntu 14.04.3 LTS and I am studying Java from the book. I tried to follow one example on the book with Ubuntu Terminal and I\'m using Sublime Text. Here is the code

8条回答
  •  离开以前
    2021-01-29 17:19

    The Math.random() method returns a Double value between 0 and 1, so you will never get a number greater or equal than 1, you will ever get a value that could be 0, but never 1. And as you are taking the residual from this value over 10, you will ever get a 0 as result.

    Math.random() % 10 will always be 0, because the random method gives you 0 <= value < 1, and when the % 10 operation takes place, you will get 0.

    Check here for more details (oracle documentation)

提交回复
热议问题