How do I generate a random negative number?

Asked

Viewed 1,435 times

3

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

  • 11

    http://www.devmedia.com.br/numeros-aleatorios-em-java-a-classe-java-util-random/26355 generates a random number , multiply by -1.

  • thanks, it worked out

  • 3

    @Motta responds.

  • 2

    @Motta would be good to put as an official answer, if he could with a line of example. I think it’s more appropriate to make your solution positive and close the matter, so Vitor could mark yours as resolved, since you’re the one who actually solved it. And the example would help other visitors.

  • 1

    Daniel Omnine has done it @Bacco.

  • 1

    @Motta didn’t have his when I mentioned it. It really would have been better yours as a matter of ethics, however if you had a lean and objective alternative, count on my vote.

  • Always remembering that in general the functions of type "Random" generate a pseudo-random number that in some applications are not recommended.

Show 2 more comments

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 has been set for demonstration purposes. A random number between 0 and 49 will be generated. So we add +1 so that the numbers are between 1 and 50.

The result obtained is multiplied by -1 because in mathematics a positive number multiplied by a negative number becomes negative. This we learn in school.

This gives the expected result. A random negative number.

There are obviously other ways to get the same result. The above example is merely illustrative. Doesn’t mean it’s the best or the only way.

Adapt the example to your needs.

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

n = 10;
n = -n;  // Resultado: -10

3

Generate a positive number and multiply it by -1;

2

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

  • I messed up, I’ve edited and fixed.

  • 1

    Thanks for the correction. :-)

  • 1

    @Paulosantos who made confusion was not Marcio? Since he is the author of this answer?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.