电脑使用一个确定的过程产生一个随机数,将从实现者,使用者的角度出发。
标准库<cstdlib>中有一个函数rand可以产生随机数。
int rand();
不需要参数,返回一个int变量,随机数是一个正数,且不大于RAND_MAX,在<cstdlib>中有它的定义。
利用标准库写一个测试random的程序
// This program tests the random number generator in C++ and produces
// the values used in the examples in the text.
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
const int N_TRIALS = 10;
int main(int argc, char *argv[])
{
cout << "On this computer, RAND_MAX is " << RAND_MAX << endl;
cout << "The first " << N_TRIALS << " calls to rand: " << endl;
for (int i = 0 ; i < N_TRIALS; ++i) {
cout << setw(10) << rand() << endl;
}
return 0;
}
输出:
On this computer, RAND_MAX is 2147483647
The first 10 calls to rand:
1804289383
846930886
1681692777
1714636915
1957747793
424238335
719885386
1649760492
596516649
1189641421
Press <RETURN> to close this window...
设置一个静态成员变量。
Like any local variable, a static local variable is accessible only within the body of the function; the difference with a static local variable is that the compiler allocates only one copy of that variable, which is then shared by all calls to initRandomSeed.
random.h
// This interface exports functions for generating pseudorandom numbers.
#ifndef RANDOM_H
#define RANDOM_H
// Returns a random integer in the range low to high, inclusive.
int randomInteger(int low, int high);
// Returns a random real number in the half-open interval [low .. high).
double randomReal(double low, double high);
// Returns true with the probability indicate by p.
bool randomChance(double p);
// Sets the internal random number seed to the specified value.
void setRandomSeed(int seed);
#endif // RANDOM_H
random.cpp
// This file implements the random.h interface
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "random.h"
/* Private function prototype */
void initRandomSeed();
/*
* Implementation notes: randomInteger
* -----------------------------------
* The code for randomInteger produces the number in four step:
* 1. Generate a random real number d in the range [0..1).
* 2. Scale the number to the range [0..N) where N is the number of values.
* 3. Translate the number so that the range starts at the appropriate value.
* 4. Convert the result to the next lower integer.
*
* The implementation is complicated by the fact that both the expression
* RAND_MAX + 1
* and the expression for the number of values
* high - low + 1
* can overflow the integer range.
* These calculations must therefore be performed using doubles instead of ints.
*/
int randomInteger(int low, int high) {
initRandomSeed();
double d = rand() / (double(RAND_MAX) + 1);
double s = d *(double(high) - low + 1);
return int(floor(low + s));
}
double randomReal(double low, double high) {
initRandomSeed();
double d = rand() / (double(RAND_MAX) + 1);
double s = d * (high - low);
return low + s;
}
/*
* Implementation notes: reanomChance
* ----------------------------------
* The code for randomChange calls randomReal(0, 1) and the checks
* whether the result is less than the requested probability.
*/
bool randomChance(double p) {
initRandomSeed();
return randomReal(0, 1) < p;
}
void setRandomSeed(int seed) {
initRandomSeed();
srand(seed);
}
void initRandomSeed() {
static bool initialized = false;
if (!initialized) {
srand(int(time(NULL)));
initialized = true;
}
}
/*
* This program plays the casino game called craps, which is
* played using a pair of dice. At the beginning of the game,
* you roll the dice and compute the total. If your first roll
* is 7 or 11, you win with what gamblers call a "natural."
* If your first roll is 2, 3, or 12, you lose by "crapping out."
* In any other case, the total from the first roll becomes your "point,"
* after which you continue to roll the dice until one of following conditions occurs:
*
* a) You roll you point again, in which case you win.
* b) You roll a 7, in which case you lose.
*
* Other rolls, including 2, 3, 11, and 12, have no effect during this phase of the game.
*/
#include <iostream>
#include "random.h"
using namespace std;
int rollTwoDice();
bool tryToMakePoint(int point);
int main() {
cout << "This program plays a game of craps." << endl;
int point = rollTwoDice();
switch (point) {
case 7: case 11 :
cout << "That's a natural. You win." << endl;
break;
case 2: case 3: case 12:
cout << "That's craps. You lose." << endl;
break;
default:
cout << "Your point is " << point << "." << endl;
if (tryToMakePoint(point)) {
cout << "You made your point. You win." << endl;
} else {
cout << "You rolled a seven. You lose." << endl;
}
break;
}
}
/*
* Rolls the dice repeatedly until you either make your point or roll a 7.
* The function returns true if you make your point and false if a 7 comes up first.
*/
bool tryToMakePoint(int point) {
while (true) {
int total = rollTwoDice();
if (total == point) return true;
if (total == 7) return false;
}
}
int rollTwoDice() {
cout << "Rolling the dice ..." << endl;
int d1 = randomInteger(1, 6);
int d2 = randomInteger(1, 6);
int total = d1 + d2;
cout << "you rolled " << d1 << " and " << d2 << " - that's " << total << endl;
return total;
}
This program plays a game of craps.
Rolling the dice ...
you rolled 6 and 4 - that's 10
Your point is 10.
Rolling the dice ...
you rolled 6 and 1 - that's 7
You rolled a seven. You lose.
Press <RETURN> to close this window...