Random c++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Random c++

hello, i got 2 questions 1. is there a "random" function in c++ 2. how i get a random value from 3 numbers(1,4,2)

26th Aug 2019, 5:37 AM
Cat Sauce
Cat Sauce - avatar
4 Answers
+ 4
Cat Sauce to get random value from 1,2 and 4; you can declare this in an array... generate random number for rand()%3 which would give you number as 0,1 or 2 randomly... use this as index of array to get number which would give you random number from array
26th Aug 2019, 5:41 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 3
Yes, v1 = rand() % 100; // v1 in the range 0 to 99 v2 = rand() % 100 + 1; // v2 in the range 1 to 100 v3 = rand() % 30 + 1985; // v3 in the range 1985-2014 You can see more details from this link, http://www.cplusplus.com/reference/cstdlib/rand/ Good Luck~
26th Aug 2019, 5:39 AM
Uchiha Itachi
Uchiha Itachi - avatar
+ 1
Cat Sauce, The standard formula should be like this, rand() % (max + 1 - min) + min Good Luck~
28th Aug 2019, 1:48 AM
Uchiha Itachi
Uchiha Itachi - avatar
0
Uchiha Itachi i found this way min = minumum number max = maximum number (rand() % (max - min)) + (min + 1) if min = 20 and max = 50 then the range is 20-50
27th Aug 2019, 1:39 PM
Cat Sauce
Cat Sauce - avatar