【问题标题】:Java Math.random not random in while loop [duplicate]Java Math.random在while循环中不是随机的[重复]
【发布时间】:2014-10-05 02:43:09
【问题描述】:

我正在运行以下代码来获取随机 (x, y) 坐标对。但是,我只能一遍又一遍地得到同一对。

int counter=0;
while(counter<20){
    x3=(int)Math.random()*831+50;
    y3=(int)Math.random()*381+50;
    canvas.setColor(Color.white);
    canvas.drawString("*", x3, y3);
    counter++;
    }

我对 Java 很陌生,所以请告诉我一个可以解决此问题的简单方法。谢谢!

【问题讨论】:

    标签: java swing random while-loop


    【解决方案1】:

    Math.random() 返回一个介于 0.0 和 1.0 之间的值。 Java 从左到右计算,导致首先计算 (int)Math.random(),然后将值截断为 0,因此 x3y3 被计算为

    x3 = 0 + 50;
    y3 = 0 + 50;
    

    用括号括住作业的第一项

    int x3 = (int) (Math.random() * 831) + 50;
    int y3 = (int) (Math.random() * 381) + 50;
    

    【讨论】:

    • 您能否解释一下为什么 OP 应该这样做?我知道这是正确的,但 OP 应该知道为什么他的代码不正确,而你的代码是正确的。
    • 这是因为 (int) 生成整数后面的任何内容吗?所以在我的代码中 (int)Math.random 总是等于 0,所以 x3 和 y3 总是等于 50?编辑:我刚刚意识到这是第二句话所说的,对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    相关资源
    最近更新 更多