如何获得范围内为负数的随机数? [英] How to get random number with negative number in range?

查看:650
本文介绍了如何获得范围内为负数的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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;.

推荐答案

使用minmax获取设置范围内的随机数:

To get 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆