1#include <iostream>
2#include <cstdlib>
3#include <ctime>
4using namespace std;
5
6int main()
7{
8 srand(time(0));
9
10 for (int i = 0; i <= 10; i++)
11 {
12 cout << rand() % 10 << " ";
13 }
14}
15
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/* rand example: guess the number */
2#include <stdio.h> /* printf, scanf, puts, NULL */
3#include <stdlib.h> /* srand, rand */
4#include <time.h> /* time */
5
6int main ()
7{
8 int iSecret, iGuess;
9
10 /* initialize random seed: */
11 srand (time(NULL));
12
13 /* generate secret number between 1 and 10: */
14 iSecret = rand() % 10 + 1;
15
16 do {
17 printf ("Guess the number (1 to 10): ");
18 scanf ("%d",&iGuess);
19 if (iSecret<iGuess) puts ("The secret number is lower");
20 else if (iSecret>iGuess) puts ("The secret number is higher");
21 } while (iSecret!=iGuess);
22
23 puts ("Congratulations!");
24 return 0;
25}
1#include <iostream>
2#include <stdlib.h>
3#include <time.h>
4using namespace std;
5int main() {
6 srand(time(NULL) );
7 const char arrayNum[7] = {'0', '1', '2', '3', '4', '5', '6'};
8 int RandIndex = rand() % 7;
9 cout<<RandIndex<<endl;
10 return 0;
11}
1#include <iostream>
2#include <ctime>
3#include <cstdlib>
4
5using namespace std;
6
7int main()
8{
9 srand((unsigned)time(0));
10 int random_integer;
11 int lowest=1, highest=10;
12 int range=(highest-lowest)+1;
13 for(int index=0; index<20; index++){
14 random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));
15 cout << random_integer << endl;
16 }
17}
1/*The problem with srand(time(NULL)) and rand() is that if you use them
2in a loop it'll probably be executed during the same clock period
3and therefore rand() will return the same number. To solve this
4you can use the library random to help you.*/
5
6#include <random>
7
8std::random_device rd;
9std::mt19937 e{rd()};
10std::uniform_int_distribution<int> dist{1, 5}; //Limits of the interval
11//Returns a random number between {1, 5} with
12dist(e);