generating random number

Apr 9, 2014 at 9:35am
Hi.. I need to generate a 5 digit random number on unix env., i have tried with rand() but it is giving same value for each time i run my binary. i tried with srand() as well but it is giving same value for same second.. Can u please suggest any alternative way to get 5 digit random number...?
Apr 9, 2014 at 9:42am
Have you used srand and set the seed using the system time?
Apr 9, 2014 at 9:45am
Yes i tried then im getting same value for single second

1
2
3
4
5
6

for(i =0; i< 10;i ++)
{
srand(time(NULL));
printf("%d \n", rand());
}


in this case some times im getting same value twice..
Last edited on Apr 9, 2014 at 9:47am
Apr 9, 2014 at 9:47am

Mine works fine, not getting same numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

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

int main()
{

	int result;

	srand(time(0));

	for (int i = 1; i <= 10; i++)
	{
		result = rand() % 10 + 1;
		cout << "Number " << i << " was " << result << endl;
	}

	return 0;

}
Apr 9, 2014 at 9:48am

dont put the srand in the loop.

Apr 9, 2014 at 9:50am
OK Thanks.. let me try
Topic archived. No new replies allowed.