问题
Consider the following code:
int rand = new Random().nextInt((30 - 20) + 1) + 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.
EDIT: Sorry, I am only half awake. The correct code is int rand = new Random().nextInt((30 - 20) + 1) + 20;.
回答1:
To get random number between a set range with min and max:
int number = random.nextInt(max - min) + min;
Also works with negative numbers
So:
random.nextInt(30 + 10) - 10;
// max = 30; min = -10;
Will yield a random int between -10 and 30.(exclusive)
Also works with doubles
回答2:
You can use Random.nextBoolean() to determine if its a random positive or negative int.
int MAX = 30;
Random random = new Random(); //optionally, you can specify a seed, e.g. timestamp.
int rand = random.nextInt(MAX) * (random .nextBoolean() ? -1 : 1);
回答3:
Okay. First, try to only create Random instance once, but for an example
int rand = -15 + new Random().nextInt(31);
is the range -15 to 15. The Random.nextInt(int) JavaDoc says (in part) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive). Note that your provided example of (30 - 20) + 1 is the range 0 to 10 (inclusive).
Edit
as a further example, to get the range 20 to 30 you would
int rand = 20 + new Random().nextInt(11);
Remember, the bounds of the result of is 0 to n.
Edit 2
30 - -10. I'm trying to make a survival simulator. That will be my temperature.
Ok. Let's write that range as -10 to 30. nextInt(n) will return a value between 0 and n so if you want the range below 0 you must subtract 10 from the result and add 10 to the n. That's
Random random = new Random();
int rand = random.nextInt(41) - 10;
Now let's examine how we can determine those numbers. Remember, nextInt() will return between 0 and n (exclusive) and we want -10 to 30 (inclusive); so 41 is n and we subtract 10. If the result is 0 (the min) we get -10, if the result is 40 (the max) we get 30.
回答4:
int randomNumber=(random.nextInt(DOUBLE_MAX)-MAX);
Alternatively, create a random positive or negative 1 and multiply it.
来源:https://stackoverflow.com/questions/27976857/how-to-get-random-number-with-negative-number-in-range