Use a random number function to randomly generate 10 integers between 0 and 99 with 0 and 99 included

1

1 Answer

It's quite simple. You need to use standart srand/rand functions. Look at this example:

#include <cstdlib> #include <iostream> #include <ctime> int main() { // initialize random generator, by current time // so that each time you run - you'll get different values std::srand(std::time(nullptr)); for(int i=0;i<10;i++) { // get rand number: 0..RAND_MAX, for example 12345 // so you need to reduce range to 0..99 // this is done by taking the remainder of the division by 100: int r = std::rand() % 100; // output value on console: std::cout << r << std::endl; } } 

And this is the modern variant of realization, using c++11. Some people like it more:

#include <random> #include <chrono> #include <iostream> int main() { auto t = std::chrono::system_clock::now().time_since_epoch().count(); std::minstd_rand gen(static_cast<unsigned int>(t)); for(int i=0;i<10;i++) std::cout << gen() % 100 << std::endl; } 
6