使用Math.random()的表达式始终返回相同的值

1 java casting

由于某种原因,这行代码int u=(int)Math.random()*6 + 1;只会返回1。

我发现它只是跳过整体(int)Math.random()*6,并且只使用1,因为当我将其更改为2时,它仅返回2。

有人知道发生了什么吗?

rge*_*man 5

的铸造Math.random()int由6乘法之前发生的转换运算符的是更高的优先级*

Math.random()方法返回介于0(包含)和1(不含)之间的随机数,因此强制转换始终返回0

要提供适当的范围,请Math.random() 在转换前通过插入括号相乘。的范围Math.random() * 60(包括)到6(不包括)。

int u = (int) (Math.random()*6) + 1;
Run Code Online (Sandbox Code Playgroud)