-5

所以我的程序的目标是模拟掷硬币。我正在尝试使用随机数生成器来生成数字 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";
    }
}
4

1 回答 1

2

您应该将 srand 函数移到 main 的开头。如果您在同一秒内调用此函数两次,您将从 random() 获得相同的数字

你也应该改变

RandNum = 2 + (rand() % 2); 

RandNum = 1 + (rand() % 2);

rand() % 2 会产生 0 或 1,所以加 1 会产生 1 或 2

于 2014-06-06T07:18:24.790 回答