How do I generate a random negative number?

3

I can not generate a random number that is negative, for example less than 0

    
asked by anonymous 25.02.2017 / 13:34

3 answers

6
import java.util.Random;

Random rand = new Random();

int n = (rand.nextInt(50) + 1) * -1;

The above example is purely didactic.

The number 50 defines the range and was placed for demonstration purposes. A random number between 0 and 49 will be generated. So we added +1 so that the numbers are between 1 and 50.

From the result obtained, multiply by -1 because in mathematics a positive number multiplied by a negative number becomes negative. This we learned in the elementary school.

This gives you the expected result. A random negative number.

There are, of course, other ways to achieve the same result. The above example is merely illustrative. It does not mean that it is the best or the only way.

Adapt the example to fit your needs.

Remembering that in JAVA we can also convert in a more summarized way:

n = 10;
n = -n;  // Resultado: -10
    
27.02.2017 / 00:20
3

Generate a positive number and multiply it by -1;

    
26.02.2017 / 22:53
2

Generate a positive number normally and then multiply by -1.

    
26.02.2017 / 23:08