Hiya, Im just a novice in C++ ...
What is the most efficient and effective method of generating a random number in C++ from a certain range of integers?
Printable View
Hiya, Im just a novice in C++ ...
What is the most efficient and effective method of generating a random number in C++ from a certain range of integers?
Code:// random numbers from 1.. 10
for(int i=0;i<10;i++) printf("%d\n",rand()%10+1);
}
Remember to call srand when your program starts, using something like srand(time(NULL)).
what does "%d" in printf do?
and can anyone briefly state the meaning of
printf("%d\n",rand()%10+1);
, I know it prints like
1
2
3
4
5
...
%d ==> decimal (i.e. integer)
rand() % 10 + 1 ==> Get a random number between 0 and 9, then add one to put it between 1 and 10.
I know your problem is resolved but I got better result using gettickcount than time.
DWORD dwStart = GetTickCount();
cout << dwStart % 10 +1<< endl;
Just an other way to do it (you need to include windows.h).
Don't use GetTickCount - it generates (semi-)predictable random numbers that aren't even random ;)
As a seed to any other generator it's ok though. The best way is to collect entropy from the system like mouse movements, time between keypresses, etc., stuff that will be pretty close to random. Under Linux (or recent ones, anyway) you can read from /dev/random to get a stream of random data :)
I heard they managed to get true random from quarks, not a pseudorandom number. Of course this technology isn't availible to the 'home user'! :D
Not from quarks, but is is a quantum effect. By putting quantum bits (e.g. a hydrogenium atom) in an undefined state, they will fall into one of the two defined states the next time you look at them - completly random and unpredictable. It works in quantum computers.
I didn't think it was quarks but I knew it had something to do with Quantum Physics. :)