2

So far, this is my code:

#include <iostream>
#include <time.h>
#include <stdio.h>      
#include <stdlib.h>  
using namespace std;

int DealerRoll(int dealerRoll)
{
        srand (time(NULL));
    for (int dealerCount = 1; dealerCount <= 3; dealerCount++)
    {
    dealerRoll = rand()% 6+1;
    cout << dealerRoll << " ";
    }
    return dealerRoll;
}
int PlayerRoll(int playerRoll)
{

        srand (time(NULL));
    for (int playerCount = 1; playerCount <= 3; playerCount++)
    {
    playerRoll = rand()% 6+1;
    cout << playerRoll << " ";
    }
    return playerRoll;
}

int main()
{
    int dealerRoll;
    int playerRoll;

    cout << "Dealer's Roll: " << endl;
    DealerRoll(dealerRoll);
    cout << endl << "Your Roll: " << endl;
    PlayerRoll(playerRoll);
system ("pause");
return 0;
}

My problem is that the Dealer and Player's random (dice) roll is always the same. The output would be something like this for example:

Dealer's Roll: 
1 6 3 
Your Roll: 
1 6 3  

How do I make the player's roll different from the dealer's like this?

Dealer's Roll: 
1 6 3 
Your Roll: 
4 2 5

1 Answers1

5

It is because you are constantly resetting your seed. This needs to be done, unintuitively, only once otherwise you will return the same seemingly random number every time. (Which actually does have specific use cases where that's what you'd want to do) To do it only once include this line once at the top of the execution, not on each successive loop through your functions.

srand (time(NULL));

Reference this other more in-depth answer on the topic.

srand() — why call it only once?

Community
  • 1
  • 1
  • Not the cause of this problem since he re-seeding with time(NULL) – Nathaniel Johnson Apr 07 '17 at 03:04
  • Nathan, in C++ at least it is done that way. Commenting out the "srand (time(NULL));" lines from his function and adding one instance of it at the top of the main makes the code work flawlessly for me. – Eric Adam Fortney Apr 07 '17 at 03:09
  • There is still a bug but I think it is in time(NULL) which may be why it isn't reseeding properly – Nathaniel Johnson Apr 07 '17 at 03:10
  • Time for bed though. Good luck! – Nathaniel Johnson Apr 07 '17 at 03:11
  • 2
    @NathanielJohnson The problem is that `time(NULL)` only returns the time accurate to each *second* so if you call `time(NULL)` more than once per second you get the same number. Obviously the time between calling these two functions is likely to be about a millionth of a second so... – Galik Apr 07 '17 at 04:30