1

I am creating a random number generator for numbers between 110,000 and 320,000. When I run it, no numbers are above 150,000. Is there some way to make sure that numbers above 150,000 are generated? Even generating thousands of numbers do not work. I am aware I have lots of things included. Here is the code:

#include <stdlib.h>
#include <iostream>
#include <Windows.h>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sstream>
#include <conio.h>
#include <ctime>
#include <random>
#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main() {
  srand((unsigned) time(0));
  int randomNumber;
  for (int index = 0; index < 500; index++) {
    randomNumber = (rand() % 320000) + 110000;
    cout << randomNumber << endl;
  }
}
mch
  • 9,424
  • 2
  • 28
  • 42
  • 3
    `rand()` generates numbers between 0 and `RAND_MAX`. The value of `RAND_MAX` is implementation defined but is only required to be as little as 32767. – john Jul 02 '20 at 06:55
  • 2
    C++ has more advanced random number generation, see [here](https://en.cppreference.com/w/cpp/numeric/random) – john Jul 02 '20 at 06:56
  • 2
    I highly recommend you watch this talk: [rand() Considered Harmful](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) – Jesper Juhl Jul 02 '20 at 07:02
  • Just in passing, `(rand() % 320000) + 110000` won't give the right range even if `RAND_MAX` is large enough -- it will run off the top of the range. The correct expression is `(rand % (320000 - 110000) + 110000`. – Pete Becker Jul 02 '20 at 13:32

1 Answers1

2

As noted by John. You could use more recent random number generators easier to manipulate.

Adapting the code from C++ Reference about uniform_int_distribution for your use case is straightforward:

#include <iostream>
#include <random>

int main(void) {
    std::random_device rd;  // Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> distrib(110000, 320000);
 
    for (int n=0; n<10; ++n)
        // Use `distrib` to transform the random unsigned int generated by
        // gen into an int in [110000, 320000]
        std::cout << distrib(gen) << ' ';

    std::cout << '\n';
}
Jean-Marc Volle
  • 3,113
  • 1
  • 16
  • 20
  • This works for generating within my limit, but is there a way to make it generate a new number every time I run it? Right now it generates the same number every time I build and run – PeePee McPeePee Jul 02 '20 at 23:39
  • Hello. This simplest and most often used way it to used current date/time as a seed. This remains prédictible (not to be used if random number are used for anything related to security) eg `mt19937 gen (time(0))` – Jean-Marc Volle Jul 03 '20 at 06:50