How does rand() and srand() working?

#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int random = rand();
cout << "\nSeed = 1, Random number = " << random;
srand(10);
random = rand();
cout << "\n\nSeed = 10, Random number = " << random;
getch();
return 0;
}
Essentially like these:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

size_t index {};
size_t MAX = 4;

void mysrand( size_t x )
{
    index = x % MAX;
}

int myrand()
{
    static int foo[] { 1, 3, 0, 2 };
    auto result = foo[index++];
    index %= MAX;
    return result;
}

int main()
{
    for ( int y=0; y<6; ++y ) {
        std::cout << ' ' << myrand();
    }
    std::cout << '\n';
    mysrand( 7 );
    for ( int y=0; y<6; ++y ) {
        std::cout << ' ' << myrand();
    }
    std::cout << '\n';
}


You should skip the rand()/srand() and focus on <random>
See http://www.cplusplus.com/reference/random/
Topic archived. No new replies allowed.