在一系列值之间生成随机双精度数-Java [英] Generate random doubles in between a range of values - Java

查看:233
本文介绍了在一系列值之间生成随机双精度数-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了这段代码,该代码会在-1和1之间生成随机双精度数。唯一的问题是,它只会生成一个随机双精度数,然后仅打印出要生成的其他双精度数。例如。如果第一个双精度数是0.51,它会一遍又一遍地打印0.51,而不是生成新的随机双精度数。

I have written this piece of code which generates random doubles in between -1 and 1. The only problem is that it only produces one random double and then just prints out that for the other doubles that I want to produce. E.g. if the first double is 0.51 it just prints 0.51 over and over again instead of generating new random doubles.

以下代码有什么问题?

public static void main(String[] args) {
    double start = -1;
    double end = 1;
    double random = new Random().nextDouble();

    for(int i=1; i<10; i++){
        double result = start + (random * (end - start));

        System.out.println(result);
    }
}

谢谢!

推荐答案

每次需要新的随机数时,必须生成新的随机数(nextDouble())。
尝试:

You must generate new random (nextDouble()) each time you want a new random number. Try:

public static void main(String[] args) {
    double start = -1;
    double end = 1;
    Random random = new Random();

    for(int i=1; i<10; i++){
        double result = start + (random.nextDouble() * (end - start));

        System.out.println(result);
    }
}

这篇关于在一系列值之间生成随机双精度数-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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