Random numbers lower than 100,000

Hello,

I need your help getting numbers from 1 to 100,000 into an array randomly with a seeded time. my output does go over the max random number i wanted to see.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <ctime>
#include <iostream>
#include <cstdlib>

using namespace std;

double GetRandom(double Min = 1, double Max = 100000)
{

    return ((double(rand()) / double(RAND_MAX)) * (Max - Min)) + Min;    
}

int main()
{
/* initialize random seed: */
  srand (time(NULL));
  int maxlist = 10000;
  int ranArray[maxlist];
  double num = 0;
  
  for (int i = 0; i < 10; ++i) 
  {
      num = GetRandom();
      if (num < 100000)
        ranArray[i] = num;
      else
      i--;
      
  }
  
  for (int i = 0; i < 10; ++i) 
  {
    cout<<ranArray[i];
    if (i < 10 - 1)
        cout<<ranArray[i]<<", ";
  }



5500355003, 1090610906, 5871058710, 6974969749, 2085520855, 3224832248, 6984369843, 8751087510, 7637276372, 45188          




Last edited on
You're printing the same number twice in a row without any spaces:
1
2
3
    cout<<ranArray[i];
    if (i < 10 - 1)
        cout<<ranArray[i]<<", ";

The value of the first element is not 5500355003, it's 55003.
5500355003

I think what you meant to do was only print the comma if the number being printed is not the last one.
1
2
3
    cout<<ranArray[i];
    if (i < 10 - 1)
        cout <<", ";


Note that your GetRandom() implementation will likely have gaps in the range it generates. RAND_MAX is often 32767, so if you stretch that onto [1;100000), you'll find that roughly 67% of the numbers in that range will never be hit.
That was it! How do I get rid of the gaps you mentioned in the range?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <random>
#include <ctime>

double GetRandom( double Min = 1, double Max = 100000 )
{
    static std::random_device rand_dev ;
    static std::mt19937 rng( rand_dev.entropy() > 0 ? rand_dev() : std::time(nullptr) ) ;
    static std::uniform_real_distribution<double> distrib ;

    return distrib( rng, std::uniform_real_distribution<double>::param_type{ Min, Max } ) ;
}

int main()
{
    for( int i = 0 ; i < 10 ; ++i ) std::cout << std::fixed << GetRandom() << '\n' ;
    std::cout << '\n' ;
    for( int i = 0 ; i < 10 ; ++i ) std::cout << std::fixed << GetRandom( 200, 700 ) << '\n' ;
}

http://coliru.stacked-crooked.com/a/94ec4d42f53ba441
https://rextester.com/FLZI93772
Topic archived. No new replies allowed.