在单个函数中调用时,rand()返回相同的值 [英] rand() returns same values when called within a single function

查看:61
本文介绍了在单个函数中调用时,rand()返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++新手,对此我感到很困惑.我需要在主函数中调用此函数3次,但是每次给我相同的结果,即pull_1,pull_2,pull_3相同.我该怎么做才能使它们实际上是随机的?

I'm a C++ newbie and I'm stumped on this. I need to call this function in my main function three times but each time it gives me the same result, i.e. pull_1, pull_2, pull_3 are the same. What do I need to do to make them actually random?

string PullOne()
{
    string pick;
    string choices[3] = {"BAR", "7", "cherries"};

    std::srand(time(0));
    pick = choices[(std::rand() % 3)];
    return pick;
}

通过我的主要功能:

string pull_1, pull_2, pull_3;
pull_1 = PullOne();
pull_2 = PullOne();
pull_3 = PullOne();

推荐答案

您不应在每次调用rand()之前先调用srand().一次调用–在程序开始的某个地方.

You shouldn't call srand() before each call to rand(). Call it once – somewhere at the start of your program.

问题是您重新启动随机生成器,以便它从相同的点开始产生完全相同的伪随机序列.

The problem is you restart the random generator so it starts to produce the very same pseudorandom sequence from the very same point.

这篇关于在单个函数中调用时,rand()返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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