給定能隨機生成整數1到5的函式,寫出能隨機生成整數1到7的函式
阿新 • • 發佈:2019-02-02
假設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; }