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

本文提供了三种使用能随机生成1到5的函数rand5,来实现随机生成1到7整数的方法。通过计算方差评估了这三种方法的均匀性,分别是:(rand5 * 5 + rand5) % 26的取模法,rand5的加权组合法,以及直接使用rand % 7 + 1的方法。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <cmath>
using namespace std;

int rand5()
{
//随机生成[1-5]之间的随机数
return (rand() % 5 + 1);
}

int rand7_1()
{
//随机生成[1-7]之间的随机数
int a;
while((a = rand5() * 5 + rand5()) > 26);
return (a - 3)/3;
}

int rand7_2()
{
//随机生成[1-7]之间的随机数
int num = rand5() + rand5() * 10 + rand5() * 100 + rand5() * 1000;
return (num % 7 + 1);
}

int rand7_3()
{
return (rand() % 7 + 1);
}

double variance(int *a, int average, int len)
{
//求方差:sqrt(sum((a[i]-平均数)^2))
double s = 0;
for(int i = 1; i < len; i++)
{
s += (a[i] - average) * (a[i] - average) ;
}
return sqrt(s);
}

int main()
{
srand((unsigned)time(NULL));
int cnt = 1000;
int a[8] = {0};
int b[8] = {0};
int c[8] = {0};
int a1, a2, a3;
int ave = cnt / 7;
while(cnt--)
{
a1 = rand7_1();
a2 = rand7_2();
a3 = rand7_3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值