Java 在一个区间内得到一个随机偶数?

Java 在一个区间内得到一个随机偶数?,java,Java,有人能解释一下这是怎么回事吗 int min = 2; int max = 10; int random = (int)(Math.random()*(max-min+1))/2*2+2; System.out.println("The number is " + random); 不确定公式部分-最大最小值+1/2*2+2 谢谢大家! 我们可以从数学上考虑这一点 这个公式就像一个数学函数: f(x) = floor(floor(x * (10 - 2 + 1)) / 2) * 2 + 2

有人能解释一下这是怎么回事吗

int min = 2;
int max = 10;
int random = (int)(Math.random()*(max-min+1))/2*2+2; 
System.out.println("The number is " + random);
不确定公式部分-最大最小值+1/2*2+2
谢谢大家!

我们可以从数学上考虑这一点

这个公式就像一个数学函数:

f(x) = floor(floor(x * (10 - 2 + 1)) / 2) * 2 + 2
int cast基本上是一个数字,整数除以2也就是一个数字

假设函数的域={0≤ x<1}我们知道这一点,因为Math.random就是这样做的,我们可以查看每个步骤,看看函数的范围是如何变化的

x * (10 - 2 + 1)
这使得范围={0≤ y<9}

floor(x * (10 - 2 + 1)) // adding floor function
这使得范围={0,1,2,3,4,5,6,7,8,9}

floor(floor(x * (10 - 2 + 1)) / 2) // dividing by two and flooring
这使得范围={0,1,2,3,4}

floor(floor(x * (10 - 2 + 1)) / 2) * 2 // multiplying by 2
这使得范围={0,2,4,6,8}

floor(floor(x * (10 - 2 + 1)) / 2) * 2 + 2 // adding 2
这使得范围={2,4,6,8,10}


如您所见,最后唯一可能的输出是2、4、6、8、10。

您也可以使用一种已经实现的方法,该方法可以使用如下方式:

int min = 2;
int max = 10;

// get local random
ThreadLocalRandom rnd = ThreadLocalRandom.current();

int randomEven = (rnd.nextInt(min, max) / 2) * 2

它不应该是+2,而应该是+min。此外,它应该是max-min+2,否则您会比其他值更不频繁地获得max值。Math.random给出一个介于0和1之间的随机值,将其乘以max-min+1将使其介于0和max-min+1之间。x/2*2看起来没用,+min将使其介于min和max+1之间。但是,由于它是一个int,1从未返回,它将给出所需的间隔。我无法理解你的问题这是一个创建统一随机整数值的糟糕方法。你应该改用nextInt方法。太棒了!正是我想要的…谢谢!顺便说一句,Math.random函数域为0≤ x<1