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

Random numbers

ive been working on a project and im fairly new to c++ and i was wondering how i could get the computer to generate a random number between 1 and 11 example of code would be: int a; int b; { cout<<"please enter a number \n"; cin>> a; if( a>b); cout<<"you win" if(a<b) cout<<"you lose" i want to have a computer generated number between 1 and 11 instead of b

21st Jan 2018, 4:31 AM
Andrew Minemann
Andrew Minemann - avatar
1 Answer
+ 12
A well-known method to generate the pseudo-random number with acceptable distribution for TEST PROJECTS is using rand() function and current system clock as the random seeder. This method has lots of problems and for the most part, criticized by professional developers. [http://wellington.pm.org/archive/200704/randomness/Lcg_3d.gif] [https://www.youtube.com/watch?v=LDPMpc-ENqY] #include <iostream> #include <cstdlib> #include <ctime> int main() { srand(static_cast<time_t>(time(0))); int low_range = 1; int high_range = 11; for (int i = 1; i <= 100; ++i) std::cout << low_range + rand() % (high_range + 1 - low_range) << std::endl; } C++ 11 introduced a more reliable pseudo-random generating algorithm in which randomness has a more uniformly distributed pattern. #include <random> #include <iostream> int main() { std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<int> dis(1, 11); for (int i = 1; i <= 10; ++i) //Use dis to transform the random unsigned int generated by gen into an int in [1, 11] std::cout << dis(gen) << std::endl; } Notice that in some online/offline compilers you get the same result on the console. That occurs because std::random_device may be implemented in terms of a pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. Discussion: [https://stackoverflow.com/questions/18880654/why-do-i-get-the-same-sequence-for-every-run-with-stdrandom-device-with-mingw] Live Link: [https://repl.it/@PERS/C-11-Random-library-sample-code]
21st Jan 2018, 5:41 AM
Babak
Babak - avatar