Random Number isn't Random

Aug 29, 2013 at 1:49pm
Hello, I've basically completed my homework exercise for class but i'm stuck with the random number generator. When executed the program will generator random numbers but when exited and opened again the same "random numbers" appear in the same order. I've looked through my notes and can't find any solutions so hints or answer /w logic (if that makes any sense) would be much appreciative.

Exercise:
Make a: roll(), setFaceValue(val), getFaceValue() and display().
roll() sets the faceValue to a random number between 1 and 6.
setFaceValue(val) sets the faceValue to the value of val
getFaceValue() returns the current faceValue
display() prints a string representation on the console.

The class has a private variable named faceValue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Dice Game.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;




class diceGame{


private:
	
	
	int  faceValue;
	

public:

	

	diceGame(){
		srand(0);
		roll();

	}


	void roll(){

		int rollVal = (rand() % 6) + 1;
        setFaceValue(rollVal);
			
	}

	void setFaceValue(int value){

		 faceValue = value;

	}

	int getFaceValue(){

		return faceValue;

	}

	 void display()
        {
            cout << "You rolled a " << getFaceValue() << endl;
        };
};



int _tmain(int argc, _TCHAR* argv[])
{

	diceGame game;
	
	game.display();

	 int rollAgain = 10;
		 while(0 < rollAgain)
    {
        game.roll();
        game.display();
        --rollAgain;
    }

	return 0;
}

Aug 29, 2013 at 1:56pm
srand(0) is your problem. Include <ctime> and initialize it with the system's time: srand(time(NULL)).
Aug 29, 2013 at 1:56pm
have a google at "random number seed".
Aug 29, 2013 at 2:20pm
Didn't knew about srand(time(NULL)) so im going to do a little research about srand(0) vs srand(time(NULL)) . I've always been using srand(0) from day 1 of the class.

But yes thanks for the help. I got it working
Aug 29, 2013 at 2:24pm
srand(0) will always start the random sequence at index 0. rand() increments to the next number in the sequence. It's not real random, it's a sequence of numbers that appears to be random. If you keep generating numbers for long enough you will see a pattern which is different for each compiler/implementation. The pattern will emerge no matter what seed you use.
Aug 29, 2013 at 2:49pm
Topic archived. No new replies allowed.