Thread: random number between 0 and variable value

1. >the word "seeds" seems strange to me<

To seed is to provide a starting point from which a series will grow.

>what is the point of modulus in all this

To limit the value that rand() returns between certain values. rand() will return a value between 0 and RAND_MAX. Normally you wouldn't want this entire range so you can use the modulus operator to obtain the remainder

rand returns - 0,1,2,3,4,5,...

rand%3 returns - 0,1,2,0,1,2,...

So rand%3 will produce values between 0->2 inclusive.

rand returns - 0,1,2,3,4,5,6
rand%4 returns - 0,1,2,3,0,1,2,3

So rand%4 will produce values between 0->3 inclusive.

rand%n will produce values between 0->(n-1) inclusive.

2. How come that modulus have this effect?

3. > How come that modulus have this effect?

Because that's the point of the operator. It gives the remainder, which is what it's doing in Joe's example.

4. Well he shows how this work with:
rand returns - 0,1,2,3,4,5,...

rand%3 returns - 0,1,2,0,1,2,...

But if you say 2/3 the remainder wont be 2 but 3...

5. >But if you say 2/3 the remainder wont be 2 but 3...

Then you need to re-take basic mathematics.

6. >> But if you say 2/3 the remainder wont be 2 but 3...
>> Then you need to re-take basic mathematics.

lol

Very helpful guys. One last request. Can I have the prototypes of srand() and time() and what header file(s) they are contained in so I know how to use them? thanks

7. Now look at this:
2/3 = 0.666...7

How come that it then produce 2 in the example.

*EDIT* I just turned to my English-Danish book and found out what reaminder means. Sorry guys

8. How does the randomness work? Does it look at a special spot in memory for a number? Is there some mathematical formula that will calculate a random number (Is that possible)?

9. >How does the randomness work? Does it look at a special spot in memory for a number? Is there some mathematical formula that will calculate a random number (Is that possible)?<

As has already been stated, it's not real randomness. Just a series of numbers that appear random (pseudorandom). The way the number is obtained is probably implementation defined, but most will take a seed (using an default seed if one is not given), and apply a series of transformations on this seed to arrive at another number. These transformations will then be applied to the previously obtained number to get the next number in the the series, and so on.

Given the seed, ideally these transformations will have to produce a series that is evenly distributed among it's range and doesn't repeat itself.

Popular pages Recent additions