簡體   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