0

I am working on a project for a class and the first step is to generate an array of 10,000 random integers.

When I write the following code:

#include<iostream>
#include<string>
#include<vector>
#include<time.h>
using namespace std;
int main()
{
    int *myarray;
    myarray = new int[10000];
    for (int i = 0; i < 9999; i++)
    {
        myarray[i] = (rand() % 10000);
        // << myarray[i] << " ";
    }
    cout << "A random array of 10,000 integers has been generated.";

        return 0;
}

The first 4 of the numbers is as follows :

0 6843 30 5756

Every time I add more body to my code or recompile these and the rest of the numbers are always the same.

Is there a way to set my random numbers to be random every single time I compile it?

This is in C++ VS 2015.

Callat
  • 2,928
  • 5
  • 30
  • 47
  • 1
    You missed to call `srand()` once. – πάντα ῥεῖ Apr 04 '16 at 19:53
  • 1
    @Hikari - You should call `srand()` before using `rand`, using something like `srand(time(NULL));`. – owacoder Apr 04 '16 at 19:55
  • 1
    you need to set the seed. srand() needs to be called ONCE. – Mike Apr 04 '16 at 19:55
  • 2
    If you don't explicitly set a seed with `srand`, `rand` will always start out with a seed of 1. `rand` is a poor choice of RNG, though, especially with the [new RNG facilities in C++11](http://en.cppreference.com/w/cpp/numeric/random). – user2357112 Apr 04 '16 at 19:55
  • 2
    @user2357112 I agree, Gaussian randoms, etc are much better than the default rand – Mike Apr 04 '16 at 19:56
  • @πάνταῥεῖ Can you please site where the duplicate is located? When I searched here and on google I wasn't able to find it. – Callat Apr 04 '16 at 19:58
  • 1
    ok So I need to use srand() to set the seed. But what is this "seed" and how does it.... Wait I should google this. Thanks for pointing me in the right direction guys! – Callat Apr 04 '16 at 19:59
  • @Hikari There's a link in the banner above your question (maybe press F5 to refresh the page). – πάντα ῥεῖ Apr 04 '16 at 20:00
  • @πάνταῥεῖ I see it now! Thank you! – Callat Apr 04 '16 at 20:01

0 Answers0