所以我的程序的目标是模拟掷硬币。我正在尝试使用随机数生成器来生成数字 1 或 2,正面为 1,反面为 2。
但是我不断得到尾巴,我哪里错了?
#include <iostream>
#include <cstdlib> // Require for rand()
#include <ctime> // For time function to produce the random number
using namespace std;
// This program has three functions: main and first.
// Function Prototypes
void coinToss();
int main()
{
int flips;
cout << "How many times would you like to flip the coin?\n";
cin >> flips; // user input
if (flips > 0)
{
for (int count = 1; count <= flips; count++) // for loop to do action based on user input
{
coinToss(); // Call function coinToss
}
}
else
{
cout << "Please re run and enter a number greater than 0\n";
}
cout << "\nDone!\n";
return 0;
}
void coinToss() //retrieve data for function main
{
unsigned seed = time(0); // Get the system time.
srand(seed); // Seed the random number generator
int RandNum = 0;
RandNum = 2 + (rand() % 2); // generate random number between 1 and 2
if (RandNum == 1)
{
cout << "\nHeads";
}
else if (RandNum == 2)
{
cout << "\nTails";
}
}