c ++时间和随机函数

时间:2012-12-12 20:59:23

标签: c++ srand time-t

我正在尝试创建一个随机抽取牌组的程序。问题是我需要使绘制过程实际上是随机的,因为当没有其他因素改变时,使用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++;
    }

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

Rob指出,问题不在于rand(),而在于{。}} 你绘制卡片的方式。每个人都没有理由 两次画同一张牌。你可以使用Rob的建议,和 洗牌,或者你可以随机挑选一张卡片 未洗过的甲板,然后将其从甲板上取下(换上甲板 结束,然后是pop_back),这样就无法重新绘制。

当然,永远不要在发电机中多次播种发电机 单一过程。