使用rand()来洗牌,但不会发生洗牌

cad*_*d4j 2 c++ random algorithm shuffle

我试图使用rand()函数来洗牌一副牌,但出于某种原因,当我试图看到洗牌的牌子看起来像是什么时,它完全没有洗牌.我不确定我错过了什么,所以任何帮助将不胜感激.

void Deck::Shuffle()
{


for (int j = 0; j <= 51; j++)
{
    srand(time(0));
    int i = 1 + rand()%52;
    int k = 1 + rand()%52;

    Card temp = theDeck[i];
    theDeck[i] = theDeck[k];
    theDeck[k]= temp;
}
}
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢大家的帮助.我修复了现在读取的代码.

 void Deck::Shuffle()
{
srand(time(0));

for (int j = 0; j <= 51; j++)
{

    int i = 1 + rand()%52;
    int k = 1 + rand()%52;

    Card temp = theDeck[i];
    theDeck[i] = theDeck[k];
    theDeck[k]= temp;
}
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 7

srand应该只在每个程序执行时调用一次,而不是每次调用时调用rand.由于现在的计算机速度很快,你的循环运行得如此之快,以至于你每次都可能获得相同的随机数,因为你不断使用相同的种子重置随机数发生器(时间,这可能不会改变)完全通过你的执行).修复它.

更新:您的修复更好,但更好的是:

int main()
{
    srand(time(0));

    // the rest of your program here.
}
Run Code Online (Sandbox Code Playgroud)