Using rand () to simulate cubes. A bit lost

This is probably a stupid question, but I'm really struggling with this concept. I am reading a tutorial on arrays and the rand () function. I have two problems.

First, obviously, to simulate a single bone, we need to randomly generate a number from 1-6. The book offers the following:

int       RollOne( void ) {
    return (rand() % 6) + 1;
}

Right, well rand () can generate any number from 0-32767. Then we find the remainder of this number when it divides by 6, then add 1. For example. 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. If I don't lose my mind, this is 9, which is not between 1-6. The program works fine, but I just can’t understand how we get a number from 1-6 using this code! Any help would be greatly appreciated.

The second problem that I have is actually not so important, but relevant. The book does not indicate what this bit of code means:

srand( clock() );

, , , srand() , , clock(). , - clock(), , ? , srand (clock()), .

, , wall'o'text. .

, Mike

ANSWERED : , . , , % , . ! , . 7/2 = 3,5, 0,5. , , , . , A -.....
!

+5
6

3245 . 6, 540,8333 .

. 3245 6 , 5 ( 0,83333 * 6 = 5).

540 * 6 = 3240, 5.

+4

:

3245 , 6, 540.8333 (- 540). 3245 - 6 * 540, 5 5 + 1 6: D

+8

rand (clock())

- , .

, ( ), /, , , (), , .

, , , , . , .

, clock() , .

, . - , , , , .

+4

srand . - - , , ​​ ( C ) Mersenne Twister, , , "" . - , , . , , , , , ​​ ( , , ).

:

:

#include <stdio.h>
int main() {
    srand(1234);
    for (int i=0; i < 20; i++) 
        printf("%d ", rand());
    printf("\n");
}

several times and watch what happens, then replace 1234 with (NULL) and watch what happens. Write a shell script that runs the modified program several times very quickly, and watch what happens.

+1
source

How can the remainder be equal to 8? Perhaps this would mean that 6 would fit into it again? % is also not a division function, it is a div function that is different.

0
source

Percentage does not divide. It gives the remainder (function "mod").

0
source

All Articles