c++获取随机数的方法

1.rand()函数

获得的随机数是唯一确定的 不是变化的

#include<iostream>
#include<ctime>
using namespace std;

int main()
{
    for (int i = 0; i < 10; i++)
    count << rand() << endl;
    return 0;
}

随机数大小是在0到rand_max,值为2147483647,它是在stdlib中实现的。如果想固定随机数的范围,通过%或/来实现。

2.srand()函数

#include<iostream>
#include<ctime>
using namespace std;

int main()
{
    srand(time(0));
    for (int i = 0; i < 1000; i++)
    count << rand() << endl;
    return 0;
}

在这里,我们需要引入ctime库,其中time(0)是获取从1970年开始的时间,然后再获取rand(),这时的rand就是随机变化的了。

但是这里获取的值是不确定的,而我们如果想获得某一范围内的值,也很简单。

#include<iostream>
#include<ctime>
using namespace std;

int main()
{
    srand(time(0));
    for (int i = 0; i < 100; i++)
    count << rand() % 100 << endl;
    return 0;
}

上述使用求余数的方法,可以获得0-100之间的值。

#include<iostream>
#include<ctime>
using namespace std;

int main()
{
    srand(time(0));
    for (int i = 0; i < 100; i++)
    count << (rand() % 10)*0.1 << endl;
    return 0;
}

上述可以获得0-1之间的数。

#include<iostream>
#include<ctime>
using namespace std;

int main()
{
    srand(time(0));
    for (int i = 0; i < 100; i++)
    if (i % 2 == 0)
        count << (rand() % 10)*0.1 << endl;
    else
        count << (rand() % 10)*-0.1 << endl;
    return 0;
}

上述可以获得-1到1之间的数。

上述程序虽然可以得到正随机数和负随机数,但是是交替出现的,还是不够随机。所以我们可以采用下面的方式。

#include<iostream>
#include<ctime>
using namespace std;
int main()
{
  srand(time(0));
  double a;
  for (int i = 0; i < 100; i++)
  if (rand() % 10 > 0.4)
  {
    cout << (rand() % 10) * 0.1 << endl;
  }
  else
  {
    a = (rand() % 10) * -0.1;
    if (a == -0.0)
    {
      cout << 0 << endl;
    }
    else
    {
      cout << a << endl;
    }
  }
  return 0;
}

  • 16
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值