最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在一系列值之间生成随机双精度数

SEO心得admin38浏览0评论
本文介绍了在一系列值之间生成随机双精度数-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); } }
发布评论

评论列表(0)

  1. 暂无评论