Reputation: 4555
I'm looking at someone else's code and trying to figure out the logic behind what they wrote. What would one use the following random number calculation for?
return ( ((rand() % 10000)+1) <= Rate * 100);
Rate
here is being used for a user-specified value representing an overall percentage of when a certain event occurs.
Upvotes: 0
Views: 105
Reputation: 36487
The left part of the expression returns a random number between 1 and 10,000 (due to the + 1
; otherwise it would be between 0 and 9,999).
Rate
can then be used to determine the effective chance of the expression being true
. The higher Rate
is, the higher the chance of returning true
.
Since Rate
is multiplied with 100, you're able to determine the Rate
using 0 to 100 (essentially percentages) with Rate = 0
never and Rate = 100
always returning true
.
Upvotes: 2
Reputation: 21351
To generate a random integer between 1 and 10000 inclusive. As for the comparison with Rate*100
who can say as you do not specify what this means.
Upvotes: 2