本文介绍了在Java中生成随机双打的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是一个Java noob,试图生成-10到10之间的随机双位。我知道int我会做以下:
I'm a Java noob trying to generate a random double between -10 and 10 inclusive. I know with ints I would do the following:
Random r = new Random();
int i = -10 + r.nextInt(21);
然而,使用双打,这不起作用:
However, with doubles, this doesn't work:
Random r = new Random();
double i = -10 + r.nextDouble(21);
有人可以解释一下双打的情况吗?
Can someone please explain what to do in the case of doubles?
推荐答案
尝试这样:
Random r = new Random();
double d = -10.0 + r.nextDouble() * 20.0;
注意:应为20.0(不是21.0)
Note: it should be 20.0 (not 21.0)
这篇关于在Java中生成随机双打的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!