Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing rand() to simulate dice. Slightly lost
    primarykey
    data
    text
    <p>This is probably a stupid question, but I'm really struggling with this concept. I'm going through a tutorial explaining about arrays and the rand() function. I have two problems. <br/><br/> The first is, obviously to simulate one dice we need to randomly generate a number from 1-6. The book suggests this:</p> <pre><code>int RollOne( void ) { return (rand() % 6) + 1; } </code></pre> <p>Right, well rand() can generate any number from 0-32767. We then find the remainder of this number when it's divided by 6, then add 1. E.g. 3245 is randomly generated. We divide it by 6, giving 540.8333 and take the remainder. 8.333 (truncated to 8 I believe) and then add 1. Unless I'm going mad, that makes 9, which is not between 1-6. The program runs fine however and I just can't understand how we get a number from 1-6 using that code! Any help would be greatly appreciated.</p> <p>The second problem I have isn't really as major, but is relevant. The book left out what this bit of code means:</p> <pre><code>srand( clock() ); </code></pre> <p>All that is mentioned is that srand() initialises a random number generator using the seed provided by clock(). Right, now can we actually input anything into clock(), if so what is its effect? Just a little explanation of what srand( clock() ) does would be perfect.</p> <p>Sorry for the long post, I hope you don't mind the wall'o'text. Any help would be really appreciated.</p> <p>Thanks, Mike</p> <p><b>ANSWERED</b> Thank you everyone: I realise what I was doing. As shown by you guys, the % operator doesn't divide, it just finds the difference between the highest multiple and the operand. Got it! I was under the impression that the remainder meant the decimal. I.e. If 7/2 = 3.5 then the remainder is 0.5. Now that I've written it out, I see how stupid I've been. Glad my A-level maths counts for something.....<br/> Thanks again!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload