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

查看:264
本文介绍了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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆