Expression with Math.random() always returns the same value

限于喜欢 提交于 2021-01-28 14:26:33

问题


For some reason this line of code int u=(int)Math.random()*6 + 1; will only return a 1 as a result.

I found out that its just skipping the whole (int)Math.random()*6 and is only using the 1 as when I changed it to 2 it only returned 2.

Anyone know What's happening?


回答1:


The cast of Math.random() to int is occurring before the multiplication by 6. The cast operator is of higher precedence than *.

The Math.random() method returns a random number between 0 (inclusive) and 1 (exclusive), so the cast always returns 0.

To provide the proper range, multiply Math.random() before the cast by inserting parentheses. The range of Math.random() * 6 is 0 (inclusive) to 6 (exclusive).

int u = (int) (Math.random()*6) + 1;



回答2:


What is happening:

  1. Math.random()Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
  2. (int)Math.random() cost the double value to 0, since type cast has a higher priority compared with *.
  3. (int)Math.random()*6 always is 0,you get what you have.


来源:https://stackoverflow.com/questions/53771414/expression-with-math-random-always-returns-the-same-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!