gpt4 book ai didi

C++时间和随机函数

转载 作者:行者123 更新时间:2023-11-30 02:01:42 27 4
gpt4 key购买 nike

我正在尝试创建一个随机从一副牌中抽牌的程序。问题是我需要让抽奖过程实际上是随机的,因为在没有其他因素改变的情况下,使用 srand 和 rand 时每次抽奖都是相同的。因此我将它附加到 time_t 秒并且能够使抽奖成为半/随机的。这是因为我必须等待一秒钟才能更改 time_t 秒的参数。这是一个问题的原因是,如果我的程序两次绘制同一张牌(众所周知),它会再次绘制。因此,如果它确实两次绘制同一张牌,它将被迫再绘制大约十五次(或更多或更少),直到 time_t 第二个参数发生变化。有没有办法测量毫秒或更小的时间单位,这样我就没有这个问题了?

这是代码,虽然没有附加检查比赛和组织程序(无论如何只发生在初始抽签之后。)

int allow = 0;
string cards[] =
{"02hearts", "03hearts", "04hearts", "05hearts", "06hearts", "07hearts", "08hearts","09hearts", "10hearts", "11hearts", "12hearts", "13hearts", "14hearts",
"02clubs", "03clubs", "04clubs", "05clubs", "06clubs", "07clubs", "08clubs", "09clubs", "10clubs", "11clubs", "12clubs","13clubs", "14clubs","14clubs",
"02spades", "03spades", "04spades", "05spades", "06spades", "07spades", "08spades", "09spades", "10spades", "11spades", "12spades", "13spades", "14spades",
"02diamonds", "03diamonds", "04diamonds", "05diamonds", "06diamonds", "07diamonds", "08diamonds", "09diamonds", "10diamonds", "11diamonds", "12diamonds", "13diamonds", "14diamonds"};
string cardHand [5];
string cardnumbers [5];
int cardInts [5];
string handSuites [5];
char handSuitesChar [5];





//check deck
while(allow == 0)
{

//set clock
time_t seconds;

time(&seconds);


srand((unsigned int) seconds);

int type;

//initiate counters
int n = 0;
int n1 = 0;
int n2 = 0;
int n3 = 0;
int n4 = 0;

//draw cards
while(n < 5)
{
type = rand() % 52;
cardHand[n] = cards[type];
cout << cardHand[n] << ", ";
n++;
}


cout << endl;

//pull numbers from cards
while(n1 < 5)
{
string character2;
cardnumbers[n1] = cardHand[n1].at(0);
character2 = cardHand[n1].at(1);
cardnumbers[n1].append(character2);
cout << cardnumbers[n1] << ", ";
n1++;
}
cout << endl;
cout << endl;


//convert numbers to ints
while(n2 < 5)
{
stringstream convert(cardnumbers[n2]);

if( !(convert >> cardInts[n2]))
cardInts[n2] = 0;

cout << cardInts[n2] + 100 << ", ";

n2++;
}

cout << endl;

//pull out first letters for suites
while (n3 < 5)
{
handSuites[n3] = cardHand[n3].at(2);

cout << handSuites[n3]<< endl;
n3++;
}


//convert letters to chars
while (n4 < 5)
{
stringstream convert(handSuites[n4]);

if( !(convert >> handSuitesChar[n4]))
handSuitesChar[n4] = 0;

cout << handSuitesChar[n4] + 100 << ", ";
n4++;
}

最佳答案

不要在循环内调用srand()。在程序开始时调用一次,然后在需要随机数时使用 rand()。这会给你一个相当长的伪随机序列。

关于C++时间和随机函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13848528/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com