【发布时间】:2017-05-30 17:50:31
【问题描述】:
我正在为我的 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
为了完成作业,我将第二个 if 语句更改为 else 语句,一切看起来都很好,但我真的很想了解这里发生了什么。
【问题讨论】:
-
if(toss == 0)==>else if(toss == 0) -
else只适用于if (toss == 0),所以当toss == 1... -
你需要使用嵌套的 if..
标签: c++ if-statement coin-flipping