rand() is only outputting 42 | Sololearn: Learn to code for FREE!


rand() is only outputting 42

hi, In my first C++ code I Tried outputting a random number. Without the #include <stdlib.h> it says it is not a function declared in that scope, but with it, it only outputs 42.. Anyone ideas? Code: https://code.sololearn.com/c9tAlW1lh9K0/?ref=app

9/15/2017 6:05:31 AM

Brent Meeusen

19 Answers

New Answer




You need to use srand() to generate new random nos everytime you run your code.. Using rand() will only create one random no, and each rime you run the code.. it will give the output as that no only...


Hope this helps- https://code.sololearn.com/cUjQX2577i0J/?ref=app


The rand () function generates random numbers based on a value called "seed" if you don't change the seed you will always get the same number. to change the seed constantly you could use the ctime library and write srand (time (NULL)); at the start of main


add library <ctime> and function srand(time(0));


Check this https://code.sololearn.com/c06L8e1iHYGL/?ref=app


do not use rand, use #include <random> and then use random_device rd; mt19937 gen (rd ()); uniform_int_distribution dist (min, max); then you assign the vaule of the dist to an int and you get a real random number. search for #include <random> and then read up on it on msdn


The Answer to the Main Question of Life (meaning of life)? :-) (For downvoters: Have you noticed how many times number "42" appears in lessons of Sololearn's courses? Do you know why? 😉)


https://code.sololearn.com/cYBlZmG9WEo8/?ref=app what you are probably using and https://code.sololearn.com/c9JTKEGIAluM/?ref=app real random numbers (they use the current time as the seed to create the next random number)


Seed it with the time. Oldest trick on the book. I don't have the book though.


42 is the answer to the meaning of life, the universe and everything, so your code works like a charm. ;-)


You sure? Usually it outputs 41.


That is because rand() don't give you an actual random number srand() gives you that


random function actually generates random numbers by a seeding unit. if seeding number is not entered computer uses default seeding to give same random number everytime. to generate different random number you need to use seeding function srand().


you have to use srand()


how to make a best WordPress website