本文介绍了math.random,只生成0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码只生成0; - ;
The following code is only producing a 0 ;-;
我做错了什么?
public class RockPaperSci { public static void main(String[] args) { //Rock 1 //Paper 2 //Scissors 3 int croll =1+(int)Math.random()*3-1; System.out.println(croll); } }编辑,另一张海报建议修复它。 int croll = 1 +(int)(Math.random()* 4 - 1);
Edit, Another Poster suggested something that fixed it. int croll = 1 + (int) (Math.random() * 4 - 1);
谢谢大家!
推荐答案您正在使用 Math.random()哪个州
返回带有正号的 double 值,大于或等于 0.0 且小于 1.0 。
你将结果转换为 int ,它返回值的整数部分,因此 0 。
You are casting the result to an int, which returns the integer part of the value, thus 0.
然后 1 + 0 - 1 = 0 。
考虑使用随机
Random rand = new Random(); System.out.println(rand.nextInt(3) + 1);更多推荐
math.random,只生成0?
发布评论