Reputation: 341
I am creating a random number from 1-100, I was looking at some Stackoverflow questions to look for the proper way and I got confused by the many different suggestions. What is the difference between using this:
int random= (int)(Math.random()*((100-1)+1));
this:
int random= (int)(Math.random()*(100);
and this:
int random= 1+ (int)(Math.random()*((100-1)+1));
Upvotes: 3
Views: 216
Reputation: 2449
int random = (int)(Math.random()*(x);
This sets random
equal to any integer between 0
and x - 1
.
int random = 1 + (int)(Math.random()*(x);
Adding 1
to the overall expression simply changes it to any integer between 1
and x
.
(int)(Math.random()*((100-1)+1))
is redundant and equivalent to
(int)(Math.random()*(100)
So take note that:
1 + (int)(Math.random()*(x)
returns an int
anywhere from 1
to x + 1
but
(int)(Math.random()*(x + 1)
returns an int
anywhere from 0
to x + 1
.
Upvotes: 5
Reputation: 34166
The first is equivalent to the second. Both will give a random integer between 0
and 99
(inclusive, because Math.random()
returns a double
in the range [0, 1)
). Note that (100-1)+1
is equivalent to 100
.
The third, will give an integer between 1
and 100
because you are adding 1
to the result above, i.e. 1
plus a value in the range [0, 100)
, which results in the range [1, 101)
.
Upvotes: 1
Reputation: 201497
I recommend that you use Random and nextInt(100) like so,
java.util.Random random = new java.util.Random();
// 1 to 100, the 100 is excluded so this is the correct range.
int i = 1 + random.nextInt(100);
it has the added benefit of being able to swap in a more secure random generator (e.g. SecureRandom). Also, note that you can save your "random" reference to avoid expensive (and possibly insecure) re-initialization.
Upvotes: 3