我已经编写了这段代码,该代码会在-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); } }