繁体   English   中英

math.random,只生成一个0?

[英]math.random, only generating a 0?

以下代码仅产生 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);

谢谢大家!

您正在使用Math.random() ,其中说明

返回一个带正号的double精度值,大于或等于0.0且小于1.0

您将结果转换为int ,它返回值的整数部分,因此为0

然后1 + 0 - 1 = 0

考虑使用java.util.Random

Random rand = new Random();
System.out.println(rand.nextInt(3) + 1);

Math.random()在范围 - [0.0, 1.0)之间生成双精度值。 然后您将结果类型转换为int

(int)Math.random()   // this will always be `0`

然后乘以30 所以,你的表达真的是:

1 + 0 - 1

我猜你想像这样放置括号:

1 + (int)(Math.random() * 3)

话虽如此,如果你想在某个范围内生成整数值,你真的应该使用Random#nextInt(int)方法。 它比使用Math#random()更有效。

你可以这样使用它:

Random rand = new Random();
int croll = 1 + rand.nextInt(3);

也可以看看:

在Java中随机生成0或1的最简单方法之一:

   (int) (Math.random()+0.5);
    or
   (int) (Math.random()*2);
public static double random()

返回带正号的双精度值,大于或等于 0.0 且小于 1.0。 返回值是伪随机选择的,具有该范围内的(近似)均匀分布。

 int croll =1+(int)Math.random()*3-1;

例如

 int croll =1+0*-1; 


System.out.println(croll); // will print always 0 

我们所有的伙伴都向您解释了意外输出的原因。

假设你想生成一个随机croll

考虑Random的分辨率

    Random rand= new Random();
    double croll = 1 + rand.nextInt() * 3 - 1;
    System.out.println(croll);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM