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