c++ – Why is the number generated by rand() always the same?

Question:

I'm using the c++ stdlib library to generate a random number with the rand() function, but every time I compile I get 41:

#include <iostream>   
#include <stdlib.h>   
using namespace std;

int main() {

    int a = rand();
    cout<<a<<endl;

    system("pause");
    return 0;
}

I'm learning C++ now and I don't know what I'm doing wrong.

Answer:

The mistake is that you never start the randon seed which you have to do with

srand(time(NULL));// que es lo mas comun, tomar el tiempo.

After that you can call rand() and get different values.

#include <iostream>   
#include <stdlib.h>
#include <ctime>//en c++
using namespace std;

int main() {
    srand(time(NULL));
    int a = rand();
    cout<<a<<endl;
    system("pause");
    return 0;
}

Try that code, it didn't compile but I'm sure it will work.

Also I think rand() returns a number between 0 – 1 and this is a double , so you have to be careful with that.

Scroll to Top