现在的位置: 首页 > 综合 > 正文

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

2013年10月01日 ⁄ 综合 ⁄ 共 287字 ⁄ 字号 评论关闭
#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

 

抱歉!评论已关闭.