本文介绍了在一个范围内生成一个随机偶数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我遵循的格式:
int randomNum = rand.nextInt((max - min) + 1) + min;这是我的代码.我正在尝试获取 1 到 100 之间的随机偶数:
So here's my code. I'm trying to get a random even number between 1 and 100:
Random rand = new Random(); int randomNum = rand.nextInt((100 - 2) + 1) + 2;我看到一种解决方案是将数字乘以 2,但这超出了预期范围.
I saw one solution is to multiply the number by 2, but that breaches the intended range.
我想过做一堆if语句来解决这个问题,但似乎过于复杂.有没有比较简单的解决办法?
I thought of doing a bunch of if statements to solve this, but it seems overly complex. Is there a relatively simple solution?
推荐答案只需生成一个从 0 到 49 的数字,然后将其乘以 2.
Just generate a number from 0 to 49 and then multiply it by 2.
Random rand = new Random(); int randomNum = rand.nextInt(100/2) *2;要在一个范围内进行,只需将范围添加到:
To do it in a range just add the range in:
int randomNum = startOfRange+rand.nextInt((endOfRange-startOfRange)/2) *2;注意 startOfRange 应该是偶数或转换成偶数.
Note that startOfRange should be an even number or converted into an even number.
更多推荐
在一个范围内生成一个随机偶数?
发布评论