假設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;}