假设rand5能随机生成1~5的5个数(均等概率),利用rand5生成rand7() 1~7(均等概率)
1. 利用rand5求出rand2(),当rand5生成的数大于2时,一直循环,直到它生成的数为1或者2,且生成1和2的概率均为1/2,因为生成1和生成2的概率是相等的。
2. 利用rand2生成0和1(减1即可),连续使用三次,共有8种可能(二进制表示):000 001 010 011 100 101 110 111,当生成的数为000时,重新计算,这样就可以得到1~7范围内的数,且概率是均等的。
#include <iostream>
#include <math.h>
using namespace std;
int rand5()
{
return rand()%5+1;
}
int rand2()
{
int temp;
do
{
temp = rand5();
} while (temp > 2);
return temp;
}
int rand7()
{
int temp;
do
{
temp = (rand2()-1)<<2;
temp += (rand2()-1)<<1;
temp += rand2()-1;
} while (temp == 0);
return temp;
}
int main(int, char **)
{
int num;
cout << "输入总生成数:";
cin >> num;
int c1, c2, c3, c4, c5, c6, c7;
c1 = c2 = c3 = c4 = c5 = c6 = c7 = 0;
for (int i = 0; i < num; i++)
{
int temp = rand7();
switch (temp)
{
case 1:
c1++;
break;
case 2:
c2++;
break;
case 3:
c3++;
break;
case 4:
c4++;
break;
case 5:
c5++;
break;
case 6:
c6++;
break;
case 7:
c7++;
}
//cout << temp << "\t";
}
cout << endl;
cout << "生成1的个数占总生成数的:" << (double)c1/num*100 << "%" << endl;
cout << "生成2的个数占总生成数的:" << (double)c2/num*100 << "%" << endl;
cout << "生成3的个数占总生成数的:" << (double)c3/num*100 << "%" << endl;
cout << "生成4的个数占总生成数的:" << (double)c4/num*100 << "%" << endl;
cout << "生成5的个数占总生成数的:" << (double)c5/num*100 << "%" << endl;
cout << "生成6的个数占总生成数的:" << (double)c6/num*100 << "%" << endl;
cout << "生成7的个数占总生成数的:" << (double)c7/num*100 << "%" << endl;
return 0;
}