由于某种原因,这行代码int u=(int)Math.random()*6 + 1;只会返回1。
我发现它只是跳过整体(int)Math.random()*6,并且只使用1,因为当我将其更改为2时,它仅返回2。
有人知道发生了什么吗?
的铸造Math.random()到int由6乘法之前发生的转换运算符的是更高的优先级比*。
该Math.random()方法返回介于0(包含)和1(不含)之间的随机数,因此强制转换始终返回0。
要提供适当的范围,请Math.random() 在转换前通过插入括号相乘。的范围Math.random() * 6是0(包括)到6(不包括)。
int u = (int) (Math.random()*6) + 1;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41 次 |
| 最近记录: |