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

编程入门 行业动态 更新时间:2024-10-09 23:16:06
本文介绍了在一系列值之间生成随机双精度数-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); } }

更多推荐

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

本文发布于:2023-11-30 06:52:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649083.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在一   精度   系列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!