PeePee McPeePee
PeePee McPeePee

Reputation: 13

Random Numbers aren't reaching limit

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;
  }
}

Upvotes: 1

Views: 106

Answers (1)

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3333

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';
}

Upvotes: 2

Related Questions