PLEASE READ THE QUESTION CAREFULLY BEFORE DECIDING IT'S BEEN ANSWERED ELSEWHERE... I'm not asking about a rand that's generating the same number... I'm asking why, when using srand, am I getting the same number? When calling roll, shouldn't the fact that I've included srand generate a new number every time roll is called? Am I implementing this incorrectly in the roll function? Please look at my code before just closing the question!
I'm writing a program meant to generate 10 random numbers between 1 and 6. I've made sure that srand() is in fact returning different numbers each time I run the program, but the same number is being generated for each roll in main. I've looked at other programs and they look to be written exactly as I've written mine. I've read through explanations on srand and rand and can't figure out what's going on here. Would really appreciate any insight! die.h
//header guards
#ifndef DIE_H
#define DIE_H
class Die {
public:
// Randomly assigns a value to roll_value in the range of 1 to 6
void roll();
// Returns roll_value
int rolled_value() const;
private:
// Stores a randomly assigned value
int roll_value;
// Die sides, initialized to 6
int sides = 6;
};
#endif
die.cpp
#include "die.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
void Die::roll() {
srand(time(0));
roll_value = rand()%sides + 1;
}
int Die::rolled_value() const {
return roll_value;
}
main.cpp
#include "die.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using std::cout;
int main() {
srand(time(0));
int random = rand();
cout<<random<<"\n";
Die die;
int i = 0;
for(i=1; i<=10; i++)
{
die.roll();
cout << "Roll #"<< i << ", Roll Value: " << die.rolled_value() << "\n";
}
return 0;
}
Output
Roll #1, Roll Value: 4
Roll #2, Roll Value: 4
Roll #3, Roll Value: 4
Roll #4, Roll Value: 4
Roll #5, Roll Value: 4
Roll #6, Roll Value: 4
Roll #7, Roll Value: 4
Roll #8, Roll Value: 4
Roll #9, Roll Value: 4
Roll #10, Roll Value: 4
Expected Output:
Roll #1, Roll Value: 6
Roll #2, Roll Value: 5
Roll #3, Roll Value: 5
Roll #4, Roll Value: 6
Roll #5, Roll Value: 5
Roll #6, Roll Value: 1
Roll #7, Roll Value: 1
Roll #8, Roll Value: 5
Roll #9, Roll Value: 3
Roll #10, Roll Value: 6