所以我的程序的目标是模拟翻转硬币。我正在尝试使用随机数生成器生成数字1或2,1为头部1,尾部2。
但是我不断收到Tails,我哪里出错了?
#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";
}
}
答案 0 :(得分:2)
你应该将srand函数移动到main的开头。 如果你在同一秒内调用此函数两次,你将从random()
获得相同的数字你也应该改变
RandNum = 2 + (rand() % 2);
到
RandNum = 1 + (rand() % 2);
rand()%2将导致0或1,因此添加1将导致1或2