我正在为我的 c++ 类制作一个抛硬币程序,我们需要制作一个函数来翻转硬币并打印出它是正面还是反面,并且每行打印 10 个。当我运行程序时,虽然我用来检测硬币是正面还是反面的 if 语句不足以从两者中挑选出来。
#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。我不明白如果我只得到两个数字,我正在检查其中一些数字不会被我的 if 语句捕获。
为了完成任务,我将第二个 if 语句更改为 else 语句,一切看起来都很好,但我真的很想了解这里发生了什么。