Random Numbers

Hi, I have used random numbers in several programs, such as blackjack, to create arrays of random integers, and I can easily generate them. However, when I try to generate a single random number, I believe that it the generator bases the randomness off of each second instead of millisecond, and it seems to be generating them in multiples of 3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
	srand( time(0) );

	int randomNumber;
	int random2;

	randomNumber = rand() % 100 + 1; //Randomness doesn't work properly here

	for (int i = 0; i < 23; i++) //In this array, random numbers work fine
	{
		random2 = rand() % 100 + 1;
		cout << random2 << " ";
	}

	cout << "\n\n" << randomNumber;

	system("pause>nul");
	return 0;
}


Does anybody know why this is happening or what I am doing wrong? Thanks.
By not working properly, what are you expecting, and what are you getting?
Since you have seeded the number with the time, the number sequences are based on an algorithm that takes the current time as an input. Hence, the first number of the sequence has a relation with the current time. The numbers in a particular sequence (i.e. the ones in the loop) are pseudorandom, not a series of numbers which are the first calls to the function.
Thanks, xkcd83, I understand now that even if I make an random number array alone, the first number is still consecutive in multiples of 3 if I repetitively start the program. Is there a way to avoid this? Ultifinitus, my random number generation goes something like this: 3, 6, 9, 9, 12, 15, ...
I just realized that my problem is that the srand reads initially from the time, but it is read in seconds, not milliseconds, so if I were to start the program twice in the same second, it will generate the same number twice. Is there any way to get it to read from milliseconds instead?
Depending on your platform, yes.

(IIRC) there are some cross platform ways to do it as well, I just don't remember what those ways are.

Windows: include windows.h
GetTickCount() will return millis
Last edited on
I don't quite understand how I implement GetTickCount into the srand, is that what I am supposed to do? Srand doesn't seem to accept variables.
srand(GetTickCount());

GetTickCount isn't a variable, sorry it's a function.
Thankyou, ultifinitus, GetTickCount() works great for me!
Topic archived. No new replies allowed.