Help random numbers rand() returns same numbers

I am trying to make a blackjack program which uses srand() with time as seed to determine random number of card between 1-10. Two problems, one is that the first three returned numbers are always similar and one digit or so more than the next three ones. They dont seen random.

Another problem is that, i have to put Sleep for 1 sec between calling the random function again because if time is same seconds, it returns the same random number. Any way i can solve it easily, because its only grade 11 project at school.

Please compile my program in devCPP and try the random number thing a few times, you will know what i mean--

``http://pastebin.com/SsiVrwpS``

THanks!!

## All 6 Replies

You only need to seed it once. So at the beginning of main, put the srand stuff. and take that out of your random function.

As firstPerson was saying, you only need to seed before you call standart rand() function.

``````// This program print out 10 numbers between 0 and 100
#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
const int NUM = 10;

srand(time(NULL));

for(int i = 0; i < NUM; i++)
{
std::cout << rand() % 100 << std::endl;
}
return EXIT_SUCCESS;
}``````

Thanks for your reply, i got it working.. just one more problem, i need to get the number quick.. but since the seed depends on time, if i call the function again within the same second, it gives me the same random number.. anyway to EASILY fix that? like by not using any fancy .h files, just calling the time in like nanoseconds or any other way so that i dont have to use Sleep("1000") to get different number.?? thanks guys

That shouldn't be the case, make sure your not seeding more than once

Yes, firstPerson is correct. `srand()` should be called only once, at the beginning of `main()` .

Thanks for your reply, i got it working.. just one more problem, i need to get the number quick.. but since the seed depends on time, if i call the function again within the same second, it gives me the same random number.. anyway to EASILY fix that? like by not using any fancy .h files, just calling the time in like nanoseconds or any other way so that i dont have to use Sleep("1000") to get different number.?? thanks guys

The time function has second granularity. You can't get any finer without switching to a non-portable (or vastly more difficult) solution. However, if you're properly seeding rand one time at the beginning of main, you shouldn't have a problem unless by "call the function" you really mean "run the program". In that case you have no choice but to use a different seed method than the time function.

However, I suspect you're still doing this:

``````int randomNumber()
{
srand(time(NULL));``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.