double random = ThreadLocalRandom.current().nextDouble(min, max);
nextDouble将在最小值(包括)和最大值(不包括)之间返回伪随机双精度值 . 边界不一定是 int ,可以是 double .
198
用这个:
double start = 400;
double end = 402;
double random = new Random().nextDouble();
double result = start + (random * (end - start));
System.out.println(result);
EDIT:
new Random().nextDouble() :随机生成0到1之间的数字 .
start :开始编号,换班号"to the right"
end - start :间隔 . Random给出了这个数字的0%到100%,因为random给出了一个从0到1的数字 .
EDIT 2: Tks @daniel和@aaa bbb . 我的第一个答案是错的 .
35
import java.util.Random;
public class MyClass {
public static void main(String args[]) {
Double min = 0.0; // Set To Your Desired Min Value
Double max = 10.0; // Set To Your Desired Max Value
double x = (Math.random() * ((max - min) + 1)) + min; // This Will Create
A Random Number Inbetween Your Min And Max.
double xrounded = Math.round(x * 100.0) / 100.0; // Creates Answer To
The Nearest 100 th, You Can Modify This To Change How It Rounds.
System.out.println(xrounded); // This Will Now Print Out The
Rounded, Random Number.
}
}
3
Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {
//do
}
-1
double var1 = LowerLimit new Random() . nextDouble()*(UpperLimit - LowerLimit); System.out.println(“\ n \ nRandom范围内的两倍是:”var1);
6 回答
要生成
rangeMin
和rangeMax
之间的随机值:这个问题是在Java 7发布之前提出的,但是现在,还有另一种使用Java 7(及以上)API的方法:
nextDouble将在最小值(包括)和最大值(不包括)之间返回伪随机双精度值 . 边界不一定是
int
,可以是double
.用这个:
EDIT:
new Random().nextDouble()
:随机生成0到1之间的数字 .start
:开始编号,换班号"to the right"end - start
:间隔 . Random给出了这个数字的0%到100%,因为random给出了一个从0到1的数字 .EDIT 2: Tks @daniel和@aaa bbb . 我的第一个答案是错的 .
double var1 = LowerLimit new Random() . nextDouble()*(UpperLimit - LowerLimit); System.out.println(“\ n \ nRandom范围内的两倍是:”var1);