如何获得范围为负数的随机数? [英] How do I get a random number with a negative number in range?
问题描述
考虑以下代码:
int rand = new Random().nextInt((30 - 20) + 1) + 20
它将返回30到20之间的一个随机数.但是,我需要它的范围包括负数.我如何在这一代中包括负数?
It will return a random number between 30 and 20. However, I need its range to include negative numbers. How would I include negative numbers in the generation?
我曾尝试使用会为负数的数学运算,但这会导致错误.简单地减去或加上负数将不会产生所需的值.
I have tried using math that would be negative, but that resulted in an error. Simply subtracting or adding the negative numbers would not yield the desired value.
对不起,我只有半醒.正确的代码是 int rand = new Random().nextInt((30-20)+ 1)+ 20;
.
Sorry, I am only half awake. The correct code is int rand = new Random().nextInt((30 - 20) + 1) + 20;
.
推荐答案
使用 min
和 max
获取设置范围内的随机数:
To get a random number between a set range with min
and max
:
int number = random.nextInt(max - min) + min;
它也适用于负数.
所以:
random.nextInt(30 + 10) - 10;
// max = 30; min = -10;
将产生一个介于-10和30(不包括)之间的随机整数.
Will yield a random int between -10 and 30 (exclusive).
它也可以用于双打.
这篇关于如何获得范围为负数的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!