随机数

本文所涉及的内容主要和C函数rand()相关。

生成随机数通常用rand()函数,自己用的不多——但是只要需要产生随机数马上想到的就是它。

#include <cstdio>
#include <stdlib.h>  //随机函数文件
#include <time.h>
using namespace std;
int main()
{
    int i;
    srand(time(NULL));//设置随机数种子——当前系统的毫秒值。  在所有的rand()前调用一次即可
    for(i = 0; i < 10; i ++)
        printf("%d\n", rand());
    return 0;
}
/*
在没有设定随机数种子之前,
rand()函数在同一个程序运行后得到的系列随机数是固定的。
产生随机数的范围是:0~0x7fff (0111 1111 1111 1111=32767)  stdlib.h中的RAND_MAX正是0x7fff
*/

如何产生0-x内的随机数?(受 zhao4zhong1 老师的启发,二进制位移解决)
32767是在2^16内,16进制表示成 0x7fff,下面是产生unsigned long long范围内随机数的代码:
#include <cstdio>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef unsigned long long ull;
ull random(){
    return ((ull)rand())&(0x00000000000000ff)
    |((ull)rand()<<8)&(0x000000000000ff00)
    |((ull)rand()<<16)&(0x0000000000ff0000)
    |((ull)rand()<<24)&(0x00000000ff000000)
    |((ull)rand()<<32)&(0x000000ff00000000)
    |((ull)rand()<<40)&(0x0000ff0000000000)
    |((ull)rand()<<48)&(0x00ff000000000000)
    |((ull)rand()<<56)&(0xff00000000000000);
}
int main()
{
    srand(time(NULL));
    for(int i=0;i<10;i++){
        ull g=random();
        printf("%020llu %016llx\n",g,g);
    }
    return 0;
}
/* output:
11750411508807810996 a311d902cb26bfb4
06274651840180911341 57140a9aa73bfced
13156436835037684249 b6950d987e492219
12353589124028619222 ab70c3db2edad9d6
10666180507130944487 9405e2a8cdbc5be7
14103711786394253231 c3ba73252284f7af
18336215526298587578 fe7752df2a0791ba
18386420766630420277 ff29b04595df1f35
17600230253063319153 f440942a46ec2e71
00013605665428757348 00305647d6d05b64

Process returned 0 (0x0)   execution time : 0.451 s
Press any key to continue.
*/

产生x内的随机数(x<=RAND_MAX):

我觉得更加常用的数据范围该是int , long long。写法:
#include <cstdio>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long LL;
LL random(LL x){
    return LL((double)rand()/RAND_MAX*x+0.5);
}
int main()
{
    LL limit=1LL<<40;  // 1099511627776
    srand(time(NULL));
    for(int i=0;i<10;i++){
        LL g=random(limit);
        printf("%013lld %010llx\n",g,g);
    }
    return 0;
}
/*output:
0377666657632 57eeafdd60
0391323728236 5b1cb6396c
0049997629487 0ba417482f
0007281533959 01b2036407
0992134168476 e6ffcdff9c
0848785260310 c59f8b3f16
0341728764222 4f909f213e
0327031474481 4c24984931
0977235545998 e387c70f8e
0965960912772 e0e7c1cf84

Process returned 0 (0x0)   execution time : 0.310 s
Press any key to continue.
*/

tc中的random()已经很少使用了,被srand(),rand()这对组合拳取代。

在随机数要求范围很小的情况下(0——32767内,可以直接用rand()%x+1产生1-x的随机数)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值