给定能随机生成整数1到5的函数,写出能随机生成整数1到7的函数。

来源:互联网 发布:桃源网络硬盘破解版 编辑:程序博客网 时间:2024/05/09 07:46
#include <iostream>#include <stdio.h>using namespace std;int rand5(){return (rand()%5+1);}void main(){int a;while((a=rand5()*5+rand5())>26);cout<< (a-3)/3<<endl;}

代码解释:

1. 通过 rand5()*5+rand5() 产生 6 7 8 9 10 11 …… 26,27 28 29 30 这25个数,每个数的出现机率相等

2. 只需要前面 3*7 个数,所以舍弃后面的4个数

3. 将 6 7 8 转化为 1,9 10 11 转化为 2,……,24 25 26 转化为 7。公式是 (a-3)/3


0 0
原创粉丝点击