私は自分の 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 ステートメントに変更しました。