在一个范围内生成一个随机偶数?

编程入门 行业动态 更新时间:2024-10-11 17:25:46
本文介绍了在一个范围内生成一个随机偶数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我遵循的格式:

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.

更多推荐

在一个范围内生成一个随机偶数?

本文发布于:2023-11-07 19:24:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1567210.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:偶数   范围内

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!