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

Question:

I'm using the c ++ stdlib library to generate a random number with the rand () function but it turns out that 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 must 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, I didn't compile it but I'm sure it will work.

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

Scroll to Top