即使以时间(0)为种子,C++ 随机数也始终相同 [英] C++ randomized number always same even with time(0) as seed

查看:50
本文介绍了即使以时间(0)为种子,C++ 随机数也始终相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成一些稍后将转换为字符的随机数.问题是 rand() 生成的数字总是返回相同的数字,尽管我使用 time(0) 作为 rand() 的种子.

Hi I'm trying to generate some random numbers which will be converted to chars later. The problem is the number generated by rand() always return the same although I've used time(0) as the seed for the rand().

int randomNumber(int min, int max)
{
    srand(time(0)); 
    int rndm = (rand()%(max-min))+min;
    cout<<rndm<<" ";
    return 0;
}

假设我随机生成 3 次

Let's say I generate the random 3 times

int main()
{
    randomNumber(0,5);
    randomNumber(0,5);
    randomNumber(0,5);
}

产生的数字将是 1 1 1 或 2 2 2 等等.知道吗?谢谢

The numbers produced will be 1 1 1 or 2 2 2 etc. Any idea? Thanks

推荐答案

您在每次调用 rand 之前用相同的种子重新播种伪随机序列,因为 返回的值>time 每秒只变化一次.这会导致您每次都得到相同的结果.

You're reseeding the pseudo-random sequence with the same seed before each call to rand, since the value returned by time only changes once a second. That causes you to get the same result each time.

仅在程序开始时调用 srand 一次.

Only call srand once, at the start of the program.

更好的是,看看 C++11 库,它有更复杂的生成器和访问真实"随机数来播种它们.

Better still, look at the C++11 <random> library, which has more sophisticated generators and access to "true" random numbers for seeding them.

这篇关于即使以时间(0)为种子,C++ 随机数也始终相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆