# Is there a better way to generate random numbers than this?

So, I was wondering how random rand() truly is, and, as it turns out, it is not very random at all.

For example, this code generates a random number between 1 - 6, and adds that occurrence to one of six counters (depending on what that number is).

#include <iostream>

int main()
{
int a = 0; int b = 0; int c = 0;
int d = 0; int e = 0; int f = 0;
for (int x = 0; x < 6000; x++) {
srand(time(NULL));
int i = 1 + rand() % 6;
if (i == 1) {a++;}
if (i == 2) {b++;}
if (i == 3) {c++;}
if (i == 4) {d++;}
if (i == 5) {e++;}
if (i == 6) {f++;}
}
std::cout << a << "\n" << b << "\n" << c << "\n";
std::cout << d << "\n" << e << "\n" << f << std::endl;

return 0;
}

However, here are some of the results I got when running the code:

Test #1:

6000

0

0

0

0

0

Test #2:

0

0

0

0

6000

0

Test #3:

0

6000

0

0

0

0

Anyway, I was wondering if there was a better way to generate random numbers, or if there is a library that can generate more random numbers than I currently am. Thanks.

answered Feb 7 by (170 points)
Wait, nevermind. I realized I included the srand(time(NULL)) inside the loop :P

Ah, yes, this is much better:

953

985

1004

1062

993

1003

Still, I'm interested to know if there are any other ways to generate random numbers. Thanks.
answered Feb 12 by (140 points)
This is about as easy as it gets:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{

int upper_lim
cout<<"Enter the upper limit number for random number seed";
cin >> upper_lim;

srand(time(NULL));

cout << (rand() % upper_lim) +1 <<endl;
cout << (rand() % upper_lim) +1 <<endl;
cout << (rand() % upper_lim) +1 <<endl;
cout << (rand() % upper_lim) +1 <<endl;
cout << (rand() % upper_lim) +1 <<endl;

return 0;
}