0

私は自分の C++ クラス用にコイン投げプログラムを作成しています。コインを投げて表か裏かを出力し、1 行に 10 を出力する関数を作成する必要があります。プログラムを実行したとき、コインが表か裏かを検出するために使用した if ステートメントでは、2 つから選択するのに十分ではありませんでした。

#include <iostream>
#include <ctime>
using namespace std;

void coinToss(int times);

int main()
{
srand(time(0));
    int times;
    cout << "How many times would you like to toss the coin?" << endl;
    cin >> times;

coinToss(times);

return 0;
}

void coinToss(int times)
{
    int toss = 0, count = 0;
    for(int i = 0; i < times;i++)
    {
        toss = rand()%2;

        if(toss == 1)//Detects if coin is heads.
        {
            cout << "H";
        }
        if(toss == 0)//Detects if coin is tails.
        {
        cout << "T";
        }

        else //I had to include this for the program to run, further explanation below the code.
        {
        cout << "Ya done goofed."; 
        }

        count++; //Counts to ten
        if(count == 10) //Skips to the next line if the coin has been tossed ten times.
        {
            cout << endl;
            count = 0;
        }
    }

}

ある時点で、表または裏を「cout << toss;」に置き換えました。返された数字は 1 と 0 だけでした。2 つの数字だけを取得している場合に、if ステートメントでキャッチされていないものがあるかどうかを確認する方法がわかりません。

課題を完了するために、2 番目の if ステートメントを else ステートメントに変更しました。

4

7 に答える 7

2

さて、rand()%2 は 1 と 0 の 2 つの数値のみを生成します。コインはブール値ジェネレーターであるため、これはあなたのタスクに沿っているようですよね? :) したがって、これはあなたが探している仕事をしているようです:

#include <iostream>
#include <ctime>
using namespace std;

void coinToss(int times);

int main()
{
srand(time(0));
    int times;
    cout << "How many times would you like to toss the coin?" << endl;
    cin >> times;

coinToss(times);

return 0;
}

void coinToss(int times)
{
    int toss = 0, Count = 0;

    for(int i = 0; i < times;i++)
    {
        toss = rand() % 2;

        // Choose:
        cout << ((toss) ? "H" : "T"); // if you want a character
        // or
        cout << toss;                 // if you want the number

        Count++; //Counts to ten
        if(Count == 10) //Skips to the next line if the coin has been tossed ten times.
        {
            cout << endl;
            Count = 0;
        }
    }
}
于 2014-10-07T09:52:37.183 に答える
0
    if(toss == 1)//Detects if coin is heads.
    {
        cout << "H";
    }
    else if(toss == 0)//Detects if coin is tails.
    {
    cout << "T";
    }

else-if ステートメントを使用する必要があります。toss==0rand()%2 は 0 または 1 になるため、else の後にも使用する必要はありません。3 番目のオプションはありません。

于 2014-10-07T09:35:02.317 に答える