【面试题】:利用rand7模拟rand10

来源:互联网 发布:出知益州 时李顺构乱 编辑:程序博客网 时间:2024/05/22 06:11

问题

已知有个rand7()的函数,返回1到7随机自然数,让利用这个rand7()构造rand10() 随机1~10。

思路

rand7只能为1-7之间的数,如何让他模拟1-10间的数呢?
肯定要通过概率性的公式进行换算才行!
首先想到的是将其扩大,扩大到多少合适呢?一想想7的倍数,还是10的倍数,想想觉得50左右即可,所以直接用:
rand7*7+rand7(这里是两个随机)
然后再写逻辑 (当然,这里也有一些逻辑上不是特别严密的地方,但这样精度差不多满足了。。)
1-5为 1
6-10为2…
…(依次类推)
40-45为9 …
46-50为10

代码

(去掉注释内容就能打印了)// rand7模拟rand10#include <iostream>#include <ctime>using namespace std;int num[11];int main(){    srand(time(NULL));    memset(num,0,sizeof(num));  //统计结果数组    for(int i=1;i<100000;i++){        int a =rand()%7,b=rand()%7+1;        if(a*7+b>=35){            if(a*7+b==35){                if(rand()%2==1){                    num[7]++;                }                else{                    num[8]++;                }            }            else if(a*7+b==40 || a*7+b==45){                // cout<<(a*7+b)/5<<endl;                 num[(a*7+b)/5+1]++;            }            else{                // cout<<(a*7+b)/5+1<<endl;                 num[(a*7+b)/5+1]++;            }        }        else{             //cout<<b<<endl;            num[b]++;        }    }    for(i=1;i<=10;i++){   //打印结果        float temp=(float)num[i]/100000;        cout<<i<<" "<<temp<<endl;    }}

结果显示

这里写图片描述
结果第一行为随机的数
第二行为 概率

0 0
原创粉丝点击