如何使Math.random舍入到数字

问题描述 投票:1回答:5

我正在制作彩票类游戏,并使用Math.random()作为数字。我希望它总是打印出与0 - 100相关的数字(因此,如果Math.random输出0.03454并且获胜的数字低于0.05,则会将标签的文本设置为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():)

java random
5个回答
1
投票

编辑:误读原帖:

你需要乘以100,然后转换为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));

%.2fformat string


1
投票

你有没有尝试过

Math.round(x)

查看此链接以获取文档:http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)

编辑:我可能没有完全理解你的问题,但我想如果你使用

Math.round(Math.random*100)

你会得到一个0到100之间的数字。


0
投票

在处理浮点数时,我更喜欢使用BigDecimal

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

0
投票

由于Math.random()返回介于0.0到1.0之间的double,因此您可以将结果乘以100.因此0.0 * 100 = 0,1.0 * 100 = 100,介于两者之间的所有内容始终在0到100之间。

使用Math.round()获取完整的整数。因此,如果随机数是0.03454,则乘以100 = 3.454。绕过它得到3。


0
投票

正确:

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

不正确的:

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

在分配给整数变量之前你需要向下转换为整数,以便不会得到如下错误:错误:不兼容的类型:可能有损转换从long到int

        int var = Math.round( Math.random() * 3);
                            ^
© www.soinside.com 2019 - 2024. All rights reserved.