+ 2
Why this rand() always showing 41 as output
4 odpowiedzi
+ 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()
+ 7
did you seed it?
+ 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 :)
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.