rand()在每个函数调用上产生相同的结果(使用srand(time(0))) [英] rand() produces the same result on each function call (with srand(time(0))

查看:77
本文介绍了rand()在每个函数调用上产生相同的结果(使用srand(time(0)))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类的成员函数,该函数应该在一定范围内生成一个随机数.为此,我正在使用rand()函数.该函数将生成一个随机数,如下所示:

I have a member function of a class that is supposed to generate a random number in a range. To do so, I am using the rand() function. The function generates a random number like this:

    unsigned seed;
    seed = time(0);
    srand(seed);
    std::cout << "Random Number: "<< rand() << std::endl;

在两个不同的对象上调用该函数.结果是:

The function is called on two different objects. The result is:

Random Number: 1321638448
Random Number: 1321638448

我每次称呼它都是一致的.我在做什么错了?

This is consistent every-time I call it. What am i doing wrong?

推荐答案

(将我的评论转换为答案).

(Converting my comment to an answer).

对于大多数应用程序,您实际上只想在运行程序的过程中为 rand 设置种子.多次播种需要您获得不同的随机种子,并且很容易将其弄乱.

For most applications, you'll only really want to seed rand once in the course of running a program. Seeding it multiple times requires you to get different random seeds, and it's easy to mess that up.

在您的情况下, time 函数通常返回分辨率为秒级的内容(尽管

In your case, the time function usually returns something with resolution on the level of seconds (though this isn't actually required by the standard). As a result, if you call time twice within the same second, you might get back the same value. That would explain why you're getting duplicate values: you're seeding the randomizer with the same value twice and then immediately querying it for a random number.

对此的最佳解决方案是仅对随机化器播种一次.通常,您可以在 main 中进行此操作.

The best solution to this is to just seed the randomizer once. Typically, you'd do that in main.

如果您确实确实想对随机化器进行多次播种,请确保您使用的随机性会很高.否则,您可能会冒这样的风险.

If you really do want to seed the randomizer multiple times, make sure that you're doing so using a seed that is going to be pretty much random. Otherwise, you risk something like this happening.

这篇关于rand()在每个函数调用上产生相同的结果(使用srand(time(0)))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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