假设rand5能随机生成1~5的5个数(均等概率),利用rand5生成rand7() 1~7(均等概率)
1. 利用rand2生成0和1,连续使用三次,共有8种可能:000 001 010 011 100 101 110 111,当生成的数为000时,重新计算,这样就可以得到1~7范围内的数,且概率是均等的。
2. 利用rand5求出rand2(),当rand5生成的数等于3时,继续rand2 (),当生成的数小于3时,返回0,生成的数大于3时,返回1,这样0和1等概率出现。
#include <iostream>
#include <math.h>
using namespace std;
int rand5()
{
return rand()%5+1;
}
int rand2()
{
int temp = rand5();
if(temp==3)
return rand2();
if(temp<3)
return 0;
if(temp>3)
return 1;
}
int rand7()
{
int temp;
do
{
temp = rand2()<<2;
temp += rand2()<<1;
temp += rand2();
} while (temp == 0);
return temp;
}
void main()
{
int num;
for(int i=0;i<10;i++)
cout<<rand7()<<endl;
}