如何在Java中生成随机正负数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3938992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:13:04  来源:igfitidea点击:

How to generate random positive and negative numbers in Java

javarandomnumbers

提问by user455497

I am trying to generate random integers over the range (-32768, 32767) of the primitive data type short. The java Random object only generates positive numbers. How would I go about randomly creating numbers on that interval? Thanks.

我正在尝试在原始数据类型 short 的范围 (-32768, 32767) 内生成随机整数。java Random 对象只生成正数。我将如何在该时间间隔内随机创建数字?谢谢。

采纳答案by pinichi

You random on (0, 32767+32768)then subtract by 32768

你随机(0, 32767+32768)然后减去32768

回答by jcopenha

Generate numbers between 0 and 65535 then just subtract 32768

生成 0 到 65535 之间的数字,然后减去 32768

回答by duggu

public static int generatRandomPositiveNegitiveValue(int max , int min) {
    //Random rand = new Random();
    int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
    return ii;
}

回答by Truth

Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);

回答by Ethan

This is an old question I know but um....

这是一个我知道的老问题,但嗯....

n=n-(n*2)

回答by UP209D

(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))

(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))

回答by Brian

In case folks are interested in the double version (note this breaks down if passed MAX_VALUE or MIN_VALUE):

如果人们对双版本感兴趣(请注意,如果通过 MAX_VALUE 或 MIN_VALUE,这会崩溃):

private static final Random generator = new Random();
public static double random(double min, double max) {
    return min + (generator.nextDouble() * (max - min));
 }

回答by Russ Hymanson

([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))

([我的双重兼容原始类型])(Math.random() * [我的最大值] * (Math.random() > 0.5 ? 1 : -1))

example:

例子:

// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));