random_shuffle 每次产生相同的结果 [英] random_shuffle produces same results every time

查看:70
本文介绍了random_shuffle 每次产生相同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试洗牌,但 random_shuffle 每次都会产生相同的结果

Im trying to shuffle a deck of cards but random_shuffle produces the same result every time

void
Deck::shuffle() {

    cout << "SHUFFLING CARDS!!!\n\n";

    srand(time(0));
    random_shuffle(cards.begin(), cards.end());

    displayCards();
}

推荐答案

那是因为你每次都给伪随机数生成器设置相同的值:

That's because you seed pseudo-random number generator to the same value each time:

srand(time(0));

time 的粒度是秒,如果我没记错的话.如果在调用 Deck::shuffle() 之间暂停执行一段时间,您应该会看到不同的结果.

The granularity of time are seconds, if I'm not mistaken. If you pause the execution for some time between calls to Deck::shuffle() you should see different results.

从函数中删除该行并在程序开始时调用一次.

Remove that line from the function and call it once at the start of your program.

这篇关于random_shuffle 每次产生相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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