Generating a random number 2.5

 1 // Die Roller
 2 // Demonstrates generating random numbers
 3 
 4 #include <iostream>
 5 #include <cstdlib>
 6 #include <ctime>
 7 
 8 using namespace std;
 9 
10 int main()
11 {
12     srand(static_cast<unsigned int>(time(0)));  // seed random number generator based on current time
13 
14     int randomNumber = rand(); // generate random number
15 
16     int die = (randomNumber % 6) + 1; // get a number between 1 and 6
17     cout << "You rolled a " << die << endl;
18 
19     return 0;
20 }

Die Roller six-sided dice throwing simulation program. Throwing calculations performed by generating a random number.

 

 rand () function

The program includes a new file: #include <cstdlib>

Cstdlib file contains (among other things) the processing of random number generation function. Because it contains the file, so you can call them free function, including the rand ().

Function is able to complete a task and a number of block values ​​returned. You can call the function after the function name by adding a pair of parentheses. If the function returns a value, the value may be assigned to a variable.

Rand () function generates a random number between 0 and at least 32767. Specific industry depends on the use of C ++ implementation.

Determine a seed for a random number generator

Computer-based pseudo-random number generated by a mathematical formula, rather than truly random numbers.

Conceivable to let the computer read the book contains a number of predetermined digital number.

To prevent always produces the same random number sequence, can tell the computer to start reading from a digital book anywhere. This process is referred to determine a seed for a random number generator.

srand(static_cast<unsigned int>(time(0)));  // seed random number generator based on current time

This line of code, determine a seed for a random number generator based on the current date and time. Because the current date and time each time the program is run is different.

Indeed, srand () function is a random number generator seed is determined, simply a value of type unsigned int is passed to it as a seed.

time (0) Return Value: a system based on digital current date and time.

ststic_cast <unsigned int> but this value is converted to unsigned int type.

Guess you like

Origin www.cnblogs.com/wlyperfect/p/12401005.html
Recommended