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

+9

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

+5

https://code.sololearn.com/cbruTEsBYLtv/?ref=app

+28

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...

+15

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

+10

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

+9

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

+7

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

+4

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

+3

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? 😉)

+2

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)

+2

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

+1

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

0

You sure? Usually it outputs 41.

0

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

0

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().

0

you have to use srand()

-4

how to make a best WordPress website