+ 2

Why this rand() always showing 41 as output

26th Apr 2017, 4:03 AM
Anil Kumar
Anil Kumar - avatar
4 Réponses
+ 12
The reason is that the random numbers provided by rand() aren't random. The rand function just takes its current numerical state, applies a transformation,saves the result of the transformation as the newstate and returns the new state. So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique. You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()
26th Apr 2017, 4:06 AM
Agus Mei
Agus Mei - avatar
+ 7
did you seed it?
26th Apr 2017, 4:04 AM
jay
jay - avatar
+ 3
The computer can not yet generate a truly random number. The rand() function has an algorithm, meaning there are steps that can be repeated to obtain a certain result so its outcome will always be thesame. You change this by using a "seed" a good "seed" in this case is time() since it is always changing. The following code snippet will help you generate an almost random number, remember, the computer cannot generate a truly random number: //add this to your includes #include <ctime> //to use time() srand(time(0));//seed the rand function note: srand(...) should be in your main function before calling rand(). Hope this helps :)
26th Apr 2017, 4:22 AM
Bill Fosam
Bill Fosam - avatar
0
The rand() function only provides pseudo random numbers , which means its actually not random. So every time the program is run, it generates the same number.
24th May 2017, 6:58 AM
Mystique
Mystique - avatar