Java随机数介于0和0.06之间 [英] Java random number between 0 and 0.06
问题描述
在Java中,我需要在 0
和 0.06
之间随机生成一个数字。
In Java, I need to randomly generate a number between 0
and 0.06
.
我在这里看到另一个问题,下面的代码可以解决这个问题:
I saw on another question on here that the following code would do the trick:
Random generator = new Random();
double number = generator.nextDouble() * .06;
然而,这样做会给我很长的数字,比如 0.007044013589130205
和 0.03656588431980957
,我认为这不是我的导师所期待的。
However, doing that gives me really long numbers like 0.007044013589130205
and 0.03656588431980957
, which I don't think is what my instructor is looking for.
有吗无论如何要生成0到0.06之间只有两位或三位小数的随机数?
Is there anyway to generate random numbers between 0 and 0.06 that only have two or three decimal places?
推荐答案
你可以这样做,如果你想要你的数字在[0; 0.06]和差异0.01之间的范围内:
You can do it this way, if you want you number to range between [0;0.06] with 0.01 of difference:
Random generator = new Random();
int number = generator.nextInt(7);
double result = number / 100.0;
您可以推广公式 number = generator.nextInt(max + 1 - min)+ min;
其中max将是您生成的最大数字,并且最小。这将从生成数字[min到max + 1]
You can generalize the formula number = generator.nextInt(max + 1 -min) + min;
where max will be the biggest number that you what to generate and min the lowest. This will generate number from [min to max+1]
要增加小数位,你只需要除数量为1000,10000等。
To increase the decimal places you just have to divide number for 1000, 10000 and so on.
这篇关于Java随机数介于0和0.06之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!