簡體   English   中英

如何使 Math.random 四舍五入到一個數字

[英]how to make Math.random round to a number

我正在制作彩票類型的游戲並使用 Math.random() 作為數字。 我希望它始終打印出你得到的與 0 - 100 相關的數字(因此,如果 Math.random 輸出 0.03454 並且獲勝的數字低於 0.05,它會將 label 的文本設置為 5)。 您如何將其四舍五入為 0.00 數字? 如果您想了解我的意思,這里有一些代碼。

public void lotterymath()
{
    double x = Math.random();
    System.out.println(x);

    if (x <= 0.02)
        output.setText("you win  " + x);
    else
        output.setText( "you lost  " + x);
}

順便說一句,我下面還有一個按鈕調用 lotterymath() :)

編輯:誤讀原始帖子

您將要乘以100,然后將其Math.round轉換為int以截斷它,或者將它Math.round

System.out.println(Math.round(x*100)); // rounds up or down

要么

System.out.println((int) (x*100));

原版的:

使用String.format(String, Object...)

System.out.println(String.format("%.2f", x));

%.2f格式字符串

你有沒有嘗試過

Math.round(x)

請查看此鏈接以獲取文檔: http : //docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)

編輯:我可能還沒有完全理解您的問題,但是我想如果您使用

Math.round(Math.random*100)

您會得到一個介於0到100之間的數字。

我更喜歡在處理浮點數時使用BigDecimal

BigDecimal myRounded = new BigDeicmal(Math.random()).setScale(2, BigDecimal.ROUND_HALF_UP);

由於Math.random()返回0.0到1.0之間的兩倍,因此您可以將結果乘以100。因此0.0 * 100 = 0、1.0 * 100 = 100,並且介於兩者之間的所有值始終在0和100之間。

使用Math.round()獲取完整的整數。 因此,如果隨機數為0.03454,則乘以100 = 3.454。 四舍五入得到3。

正確:

int var = (int)Math.round(Math.random()*100)

不正確的:

int var = Math.round(Math.random()*100)

您需要先向下轉換為整數,然后再分配給整數變量,以免出現如下錯誤:錯誤:不兼容的類型:可能從long到int的有損轉換

        int var = Math.round( Math.random() * 3);
                            ^

當您創建變量時,將其乘以 100,如下所示:

double a = Math.random()*100;

然后當你必須打印它時,在變量前放一個(int)就像下面這樣:

System.out.print((int)a);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM