給定能隨機產生整數1到5的函數,寫出能隨機產生整數1到7的函數

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.