简体   繁体   English

math.random,只生成一个0?

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

The following code is only producing a 0 ;-;以下代码仅产生 0 ;-;

What am I doing wrong?我究竟做错了什么?

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);
  }
}

Edit, Another Poster suggested something that fixed it.编辑,另一张海报建议了一些修复它的东西。 int croll = 1 + (int) (Math.random() * 4 - 1); int croll = 1 + (int) (Math.random() * 4 - 1);

Thanks, everyone!谢谢大家!

You are using Math.random() which states您正在使用Math.random() ,其中说明

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .返回一个带正号的double精度值,大于或等于0.0且小于1.0

You are casting the result to an int , which returns the integer part of the value, thus 0 .您将结果转换为int ,它返回值的整数部分,因此为0

Then 1 + 0 - 1 = 0 .然后1 + 0 - 1 = 0

Consider using java.util.Random考虑使用java.util.Random

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

Math.random() generates double values between range - [0.0, 1.0) . Math.random()在范围 - [0.0, 1.0)之间生成双精度值。 And then you have typecasted the result to an int :然后您将结果类型转换为int

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

And then multiply by 3 is 0 .然后乘以30 So, your expression is really:所以,你的表达真的是:

1 + 0 - 1

I guess you want to put parenthesis like this:我猜你想像这样放置括号:

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

Having said that, you should really use Random#nextInt(int) method if you want to generate integer values in some range.话虽如此,如果你想在某个范围内生成整数值,你真的应该使用Random#nextInt(int)方法。 It is more efficient than using Math#random() .它比使用Math#random()更有效。

You can use it like this:你可以这样使用它:

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

See also:也可以看看:

One of the easiest ways to randomly generate 0 or 1 in Java: 在Java中随机生成0或1的最简单方法之一:

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

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.返回带正号的双精度值,大于或等于 0.0 且小于 1.0。 Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.返回值是伪随机选择的,具有该范围内的(近似)均匀分布。

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

eg例如

 int croll =1+0*-1; 


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

All our mates explained you reasons of unexpected output you got.我们所有的伙伴都向您解释了意外输出的原因。

Assuming you want generate a random croll假设你想生成一个随机croll

Consider Random for resolution考虑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