1std::srand(std::time(nullptr)); // set rand seed
2v1 = std::rand() % 100; // v1 in the range 0 to 99
3v2 = std::rand() % 100 + 1; // v2 in the range 1 to 100
4v3 = std::rand() % 30 + 1985; // v3 in the range 1985-2014
1#include <cstdlib>
2#include <iostream>
3#include <ctime>
4
5int main()
6{
7 std::srand(std::time(nullptr)); // use current time as seed for random generator
8 int random_variable = std::rand();
9 std::cout << "Random value on [0 " << RAND_MAX << "]: "
10 << random_variable << '\n';
11}
1#include <cstdlib>
2#include <iostream>
3#include <ctime>
4
5int main()
6{
7 std::srand(std::time(nullptr)); // use current time as seed for random generator
8 int random_variable = std::rand();
9 std::cout << "Random value on [0 " << RAND_MAX << "]: "
10 << random_variable << '\n';
11
12 // roll 6-sided dice 20 times
13 for (int n=0; n != 20; ++n) {
14 int x = 7;
15 while(x > 6)
16 x = 1 + std::rand()/((RAND_MAX + 1u)/6); // Note: 1+rand()%6 is biased
17 std::cout << x << ' ';
18 }
19}
1v1 = rand() % 100; // v1 in the range 0 to 99 --Credit goes to Clever cowfish
2v2 = rand() % 100 + 1; // v2 in the range 1 to 100
3v3 = rand() % 30 + 1985; // v3 in the range 1985-2014