循环播放一对卡片100次(卡片组)

时间:2018-07-18 18:48:45

标签: c++ string

int main()
{
    srand(time(NULL)); //seeding rand with a starting value


    const string ranks[] = { "Ace",   "Two",  "Three", "Four", "Five",  "Six", "Seven",
                             "Eight", "Nine", "Ten",   "Jack", "Queen", "King" };

    const string suits[] = {
        "Diamonds", "Hearts", "Spades", "Clubs"
    }; //array with 52 cards,4 suits each with 13 ranks(1 to King)

    int ranksindex = rand() % 13; //random index for drawing card 1
    int suitsindex = rand() % 4;

    int ranksindex2 = rand() % 13; // random index for drawing card 2
    int suitsindex2 = rand() % 4;

    string card1, card2;
    int    counter = 0;
    int    times   = 1000;
    int    i;

    for (i = 0; i < times; i++)
    {
        card1 = ranks[ranksindex] + " of "
                + suits[suitsindex]; // two random cards with the ranks and suits
        card2 = ranks[ranksindex2] + " of " + suits[suitsindex2];

        if (card1 == card2)
        {
            card2 = ranks[ranksindex] + " of "
                    + suits[suitsindex]; // to make the cards always different
        }

        cout << "The two cards drawn are : " << card1 << " and " << card2 << endl
             << endl; //display card the two cards drawn
    }
}

当我尝试运行程序时,它没有完成程序,卡在了那里,我该怎么办才能解决此问题?

下面是我的输出的图片,它将运行但不会完成整个程序并显示计数器

2 个答案:

答案 0 :(得分:3)

int ranksindex = rand() % 13; //random index for drawing card 1
int suitsindex = rand() % 4; 

int ranksindex2 = rand() % 13; // random index for drawing card 2
int suitsindex2 = rand() % 4;

上面的代码应该在for循环内。

您想每转查找随机的ranksIndex和suitsIndex。现在,您只找到它一次,并在for循环中多次使用它。

答案 1 :(得分:0)

重新格式化代码后可以看到,随机值是在循环外部读取的,因此必须将此代码移入循环内部。


我相信,通过获得2个随机数,所选卡的结果分布将不太均匀。

由于您要查找52张卡中的1张,因此只能生成1个随机值,然后将该值映射到一张卡上。

这里是一个例子:

constexpr auto card_ranks_count = 13;
constexpr auto card_suits_count = 4;

const int random_card = rand() % (card_ranks_count * card_suits_count);

const auto indexes = std::div(random_card, card_ranks_count);

const int ranksindex = indexes.rem;
const int suitsindex = indexes.quot;