c 语言获取随机字符串,C++常见获取随机数的方法小结

本文实例讲述了C++常见获取随机数的方法。分享给大家供大家参考,具体如下:

方法一:

使用 rand 函数可以获取,如下。

#include

#include

using namespace std;

int main()

{

for (int i = 0; i < 10; i++)

cout << rand() << endl;

return 0;

}

9a06c62f2614ef57d84837ab6e1c2c3c.png

随机数大小是在0到RAND_MAX,值为2147483647,它是在stdlib中定义的,如果我们希望在某个范围内,可以使用 % 结合 / 来实现。

但是不难发现,这里获得的随机数是唯一确定的,而不是变化的。所以,如果我们希望获得变化的随机数,可以使用下面的方法。

方法二:

既然使用rand函数无法获取到变化的随机数,这里就可以使用srand来实现了。

#include

#include

using namespace std;

int main()

{

srand(time(0));

for (int i = 0; i < 1000; i++)

cout << rand() << endl;

return 0;

}

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

6c4d25cdae7568aec82bf159e26d964c.png

但这里获取的值是不确定的,而如果我们希望获得在某一范围内的值呢,也很简单,如下所示:

#include

#include

using namespace std;

int main()

{

srand(time(0));

for (int i = 0; i < 100; i++)

cout << rand() % 100 << endl;

return 0;

}

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

而如果我们希望得到0 -  1之间的数呢? 如下所示:

#include

#include

using namespace std;

int main()

{

srand(time(0));

for (int i = 0; i < 100; i++)

cout << (rand() % 10) * 0.1 << endl;

return 0;

}

而我们希望得到-1 到 1 之间的数呢?

#include

#include

using namespace std;

int main()

{

srand(time(0));

for (int i = 0; i < 100; i++)

if (i % 2 == 0)

cout << (rand() % 10) * 0.1 << endl;

else

cout << (rand() % 10) * -0.1 << endl;

return 0;

}

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

#include

#include

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;

}

这样,我们就可以得到真正的随机数了,后面使用 a == -0.0 判断是为了防止输出 -0 的情况。 最终结果如下:

51bd113b7eade2527a1a67875f127565.png

PS:这里再提供几款相关工具供大家参考使用:

希望本文所述对大家C++程序设计有所帮助。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值