Reputation: 331052
I am using an internal language in my company and they only have Random()
that returns a float between 0 and 1.
I need to port a piece of C++ code that use rand()
:
int b = rand() % (i+1);
I looked at the docs, but not sure how I can use my Random()
to generate a number between 0 and i+1
which is what the above code does, right?
I tried multiplying i+1
with Random()
but didn't get the same results, that's why I am not sure if what I am doing is correct.
I expect difference between the results due to different random functions, but still I want to be sure I am translating it correctly.
Upvotes: 1
Views: 154
Reputation: 484
Rand() give you a number between 0 and RAND_MAX, which after applying the mod operator you end up with a number between 0 and i (including i).
To do the same with Random() you'll need to multiply by ( i+1 ), then take the floor of that (round down):
b = floor( Random() * (i+1) )
This will give you a number from 0 to i (including the fence posts) as required.
Upvotes: 2
Reputation: 455062
You need to multiply Random()
with i
and not i+1
.
C++ rand()
returns an integer between 0
and RAND_MAX
but your Random()
returns a float between 0
and 1
, so multiplying the output of Random()
with i
and taking the integer portion of the result will give you an integer in [0,i]
which is what rand() %(i+1)
gives.
Upvotes: 4