java 在特定范围内在Java中生成十进制随机数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27531759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating decimal random numbers in Java in a specific range?
提问by Omid7
How can I generate a random whole decimal number between two specified variables in java, e.g. x = -1 and y = 1 would output any of -1.0, -0.9, -0.8, -0.7,….., 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.9, 1.0?
如何在java中的两个指定变量之间生成随机整数十进制数,例如 x = -1 和 y = 1 将输出 -1.0, -0.9, -0.8, -0.7,....., 0, 0.1, 0.2 中的任何一个, 0.3, 0.4, 0.5, 0.6, 0.7, 0.9, 1.0?
Note: it should include 1 and -1 ([-1,1]) . And give one decimal number after point.
注意:它应该包括 1 和 -1 ([-1,1]) 。并在点后给出一个十进制数。
回答by Marv
Random r = new Random();
double random = (r.nextInt(21)-10) / 10.0;
Will give you a random number between [-1, 1] with stepsize 0.1.
会给你一个 [-1, 1] 之间的随机数,步长为 0.1。
And the universal method:
和通用方法:
double myRandom(double min, double max) {
Random r = new Random();
return (r.nextInt((int)((max-min)*10+1))+min*10) / 10.0;
}
will return doubles with step size 0.1 between [min, max].
将在 [min, max] 之间返回步长为 0.1 的双精度数。
回答by WannabeCoder
If you just want between -1 and 1, inclusive, in .1 increments, then:
如果您只想在 -1 和 1 之间(含),以 0.1 为增量,则:
Random rand = new Random();
float result = (rand.nextInt(21) - 10) / 10.0;