您的位置:首页 > 职场人生

面试题79:抽奖算法实现

2016-04-13 15:12 295 查看
题目:

一个商场进行一场抽奖活动,其中有两个奖项,第一个奖项A抽中的概率是1/6,第二个奖项B抽中的概率是5/6;编码实现这个抽奖程序。

思路:

这题考察队随机函数的应用。

由于rand()函数产生的随机数的范围是0-65535,那么将该随机数对6求余,得到的数在0-5之间,且每个数出现概率相等。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;

char Draw()
{
int num = rand() % 6;
if (num == 0) return 'A';
else return 'B';
}

int main()
{
srand((unsigned int)time(0)); //注意:srand函数一定不能在循环里
for (int i = 0; i < 36; i++)
{
cout << Draw() << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: