Random number generation

Hello,

I am trying to generate a random number from (and including) 1-8, but I only ever seem to get the same ones and I'm not sure 8 is coming up, I'm not looking for anything too complicate if possible.

So far I am using something that looks like this:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "stdafx.h"
#include "math.h"
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std; 



int main()
{
	int RandRoll=0;
	RandRoll=rand() % 8 + 1;
	cout<<"Random roll = "<<RandRoll<<endl;
	return 0;
}





Any help is greatly appreciated =)

Thank you.
Last edited on
You need to seed (initialize) the RNG at the start of the program.

Do this once when the program starts:

1
2
3
4
5
6
int main()
{
    // do this only once:
    srand( (unsigned)time(0) );

    //... 


Note again.. you should not do this before every single call to rand()... you should only do it once.


For why this is necessary and for more info on how rand works... I made a big post about it recently here:

http://www.cplusplus.com/forum/general/130163/#msg702613
Ok thats great, thank you very much =)
Topic archived. No new replies allowed.