1

I am trying to use the rand() which can generate a random number. However, I found that the code keep giving the same number when every time I compile it. Here is the code:

#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
    int a = rand() % 11;
    cout << a;
    return 0;
}
SCMS
  • 51
  • 5
  • 2
    Does this answer your question? [Generate random numbers using C++11 random library](https://stackoverflow.com/questions/19665818/generate-random-numbers-using-c11-random-library) – ShadowMitia Dec 30 '19 at 08:16
  • You can use `srand(time(0))` function as a seed. If you don't use C++11 or after. – shalom Dec 30 '19 at 08:20
  • @ShadowMitia I tried this but it is not sui for my compiler. Thanks for helping!! – SCMS Dec 30 '19 at 08:21
  • 1
    @SCMS You can try adding -std=c++11 to make it work, unless you can't use c++11 and beyond. But C++11 would make your life easier. – ShadowMitia Dec 30 '19 at 08:22
  • @SCMS what's your compiler. Most modern compilers already support C++11 – phuclv Dec 30 '19 at 08:25

2 Answers2

3

What you can do is include the:#include<time.h> and use srand at the top of main. This will correct this issue because it will specify the seed for the generator.

// top of main
srand(static_cast<unsigned int>(time(0)));

time(0) provides you with the seconds that have passed since Jan 1, 1970. This provides a good seed.

When you have time look into the <random> header here

bhristov
  • 3,137
  • 2
  • 10
  • 26
2

You have to seed it at least 1 change to get random numbers every time you run the file:

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
    srand(time(0));
    int random = rand();
    cout << "Seed = " << time(0) << endl;
    cout << "Random number = " << random << endl;
return 0;
}
Ixtiyor Majidov
  • 301
  • 4
  • 11