The function rand().

Hello guys. I'm making a little progran in which i need to generate random numbers. I've heard of the function
rand()
, which is suposed to do what i need. But when i run the following code i wrote to get used to the syntaxis and to learn to manipulate the function, i get the same "random" number each time i compile:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int random;
    
    
    
    random=rand();
    
    cout<<random<<endl;
    
    
    
    system("PAUSE");
    return EXIT_SUCCESS;
}


I wanted to know if i'm using the function in the right way, or if there is a function that each time i run my programm generates random numbers each time. Once again gauys, thank you for your help!
Hi.

rand() is a function that you'll need to seed with srand(unsigned int), otherwise it'll be rather predictable in its output. A lot of us do this using srand(time(0));, which requires you to #include <time> but has the benefit of generating much less predictable results that change each time.

Happy programming!

-Albatross
Topic archived. No new replies allowed.