題目:已知rand7() 可以產生 1~7 的7個數(均勻概率),利用rand7() 產生rand10() 1~10(均勻概率)

<span style="font-size:18px;">int rand10()
{
int temp;
int temp2;
do 
{
temp = rand7();
} while (temp > 5);//temp 1到5
do 
{
temp2 = rand7();
while (temp2 > 2);//temp2 1到2
return temp + (temp2 - 1) * 5;</span>
}
同理,當有rand5()時,產生1-7的隨機數代碼如下:
<pre name="code" class="cpp">int rand5()
{
    return (rand() %5 +1);
}

int rand10()
{
    int res,tmp;
    do{
        res = rand5();
    }while(res > 4);
    do{
        tmp = rand5();
    }while(tmp > 2);
    return res + (tmp-1)*3;
}

int main()
{
    srand((unsigned int) time(0));
    for(int i = 0;i<10;i++)
    {
        cout << rand10() << endl;
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章