I'm learning to write in c ++, but I got stuck on the random-code creation code. How to implement it?

Closed due to the fact that the question is too general among participants Vladimir Martyanov , αλεχολυτ , rjhdby , aleksandr barakin , Kirill Stoianov Oct 8 '16 at 11:11 .

Please correct the question so that it describes the specific problem with sufficient detail to determine the appropriate answer. Do not ask a few questions at once. See “How to ask a good question?” For clarification. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    There are dozens of different generators of "random" values. Your question is too extensive due to this. - Vladimir Martyanov

2 answers 2

A new way (C ++ 11) - use the library random

Trivial usage example:

 #include <random> std::default_random_engine generator; std::uniform_int_distribution<int> distribution(1,6); int dice_roll = distribution(generator); // generates number in the range 1..6 

The old method (coming from C), which is not recommended for use in modern C ++ code:

 #include <stdlib.h> // srand, rand #include <time.h> // time srand(time(0)); int random_number = rand(); 
  • thanks for libu) - Flippy
  • one
    Moreover, the function srand (time (0)); need to call only once in the entire program. - Alexander
  • First you need to bring the solution to C ++ 11, and then, with reservations and a small font, this outdated rand() method. And certainly not the other way around. - ixSci
  • one
    @ixSci in C ++ 11 solution may be too different, depending on the needs of the applicant. But I need my own code, and it needs a completely different distribution. In the manual there are plenty of examples for all (standard) cases of life. - andy.37
  • Well, with rand you didn’t have such a dilemma, and there the distribution isn’t indicated at all, just like how correctly rand can be used so that it gives at least some sort of uniform distribution. Why produce an outdated solution? - ixSci
 #include <random> #include <ctime> srand(time(0)) //без этого будут одни и те же значения a = rand()%10+1; //рандом от 1 до 10