我需要帮助制作一个可以同时掷 2 个硬币的程序

I need help making a program that will flip 2 coins at the same time

本文关键字:程序 硬币 帮助 一个      更新时间:2023-10-16
for (int i = 0; i < input; ++i)
{
    if (rand() % 2 == 1)
    {
        cout << "H" << endl;
        heads++;
    }
    else(rand() % 2 == 2);
    {
        cout << "T " << endl;
        tails++;
    }
}

我做了一个 for 循环,但无法让程序翻转 2 个硬币,所以响应看起来像这样。

How many times would you like to flip the coins?
2
H T
H H
for (int i = 0; i < input; ++i)
{
    for (int j = 0; j < 2; ++j)
    {
        if (rand() % 2 == 1)
        {
            cout << "H ";
            heads++;
        }
        else
        {
            cout << "T ";
            tails++;
        }
    }
    cout << endl;
}

您要做的是创建两个分配随机值的局部变量,并对每个变量执行两次检查:

for(int i=0; i<input; ++i)
{
    int first_coin = rand();
    int second_coin = rand();
    (first_coin%2==0) ? (heads++, cout<<"H ") : 
                        (tails++, cout<<"T ");
    (second_coin%2==0) ? (heads++, cout<<"H ") : 
                         (tails++, cout<<"T ");
}
cout << endl;

您可以在此处运行此示例。

这是一个简单的数学错误。 任何事物的模数永远不能等于任何大于 0 或 1 的数字,因此当它不应该打印时,它将继续打印 '% == 1' 语句。