mercredi 15 juillet 2020

Why does the random number generator not randomize numbers in the void function but does in the main function?

#include <iostream>
#include <cstdlib> 
#include <iomanip>
#include <ctime>
using namespace std;

void coinToss();

int main()
{

cout << "How many times do you want to flip the coin?\n";
   
int choice;
   
cin >> choice;

   for (int i = 1 ; i <= choice; i++)
   {
       cout << "Rolling Dice # " << i << endl;
       coinToss();

   }
   return 0;
}

void coinToss()
{
   
unsigned seed = time(0);
   
srand(seed);

   int result;
   result = (rand() % (2 - 1 + 1)) + 1;
   if (result == 2)
       cout << "Tails\n";
   else
       cout << "Heads\n";
       cout << endl;
}

When I do this it does not randomize the number and just gives the same number over and over. But if i put "unsigned see = time(0); srand(seed);" in my main function it actually randomizes and gives out different numbers?




Aucun commentaire:

Enregistrer un commentaire