1,一般情况,生成随机数采用以下方式:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int iSecret, iGuess;
/* initialize random seed: */
srand ( time(NULL) );
/* generate secret number: */
iSecret = rand() % 10 + 1;
do {
printf ("Guess the number (1 to 10): ");
scanf ("%d",&iGuess);
if (iSecret<iGuess) puts ("The secret number is lower");
else if (iSecret>iGuess) puts ("The secret number is higher");
} while (iSecret!=iGuess);
puts ("Congratulations!");
return 0;
}
2,但是实际这种方式生成的随机数并不是很随机,有时候随机变化的幅度很小,而《Accelerated C++》提供了一种不错的方式:
// return a random integer in the range `[0,' `n)'
int nrand(int n)
{
if (n <= 0 || n > RAND_MAX)
throw domain_error("Argument to nrand is out of range");
const int bucket_size = RAND_MAX / n;
int r;
do r = rand() / bucket_size;
while (r >= n);
return r;
}
3,上面这种方式比较完美,但是稍微有一点不足,那就是只是生成小于RAND_MAX(32767)的随机数,《Accelerated C++》练习题中提供了一种改进的方式:
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <limits.h>
using namespace std;
#define MY_RAND_MAX 32767
int nrand(int n) {
if (n <= 0)
throw domain_error("Argument to nrand is out of range");
int r;
if (n <= MY_RAND_MAX) {
const int bucket_size = MY_RAND_MAX / n;
do {
int bucket = rand() / bucket_size;
r = bucket;
} while (r >= n);
} else {
const int bucket_size = ceil(n / MY_RAND_MAX);
do {
const int bucket = nrand(MY_RAND_MAX);
const int remainder = nrand(bucket_size);
r = (bucket - 1) * bucket_size + remainder;
} while (r >= n);
}
return r;
}
int main() {
int limit;
while (cin >> limit)
cout << nrand(limit) << endl;
return 0;
}
这种方式真的接近完美了,只是算法稍微复杂点。