本文介绍了rand() 在单个函数中调用时返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我是 C++ 新手,对此我很困惑.我需要在主函数中调用这个函数三次,但每次都给我相同的结果,即 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() 在单个函数中调用时返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)