0

I'm trying to generate a random from 1 - 99,999,999 However, its not ever getting that high. I believe it has something to do with the size of an int.

Here is what I'm trying

(1 + rand() % 99999999)

Thanks

Eric
  • 2,008
  • 3
  • 18
  • 31
  • what platform/compiler? – Jim Garrison Nov 01 '13 at 04:15
  • 2
    `RAND_MAX` is most likely 32k. Use ``. It's a lot better anyway. – chris Nov 01 '13 at 04:17
  • I'm pretty sure an `int` can contain much more than that. – Shoe Nov 01 '13 at 04:17
  • 4
    Apart from being a terrible formula, I don't suppose you know the value of RAND_MAX for your current implementation? Methinks thats about the limit you will see using this mechanism. (and in case you're using VC++, their 32bit RAND_MAX is only 0x7FFF, or 65535). See [](http://en.cppreference.com/w/cpp/numeric/random) in the C++ 11 standard library, and use *that*. It's much more robust than the crap-legacy interface and manages the modulus probability balancing for you. `std::random_device` + `<>` + `std::uniform_int_distribution` together do exactly what you want. – WhozCraig Nov 01 '13 at 04:17
  • 1
    If you have access to c++11 - http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful - Don't use rand. – David Nov 01 '13 at 04:31

2 Answers2

1

your code will not work because value returned by rand have a maximum value RAND_MAX

int rand (void);

Generate random number Returns a pseudo-random integral number in the range between 0 and RAND_MAX.


RAND_MAX

Maximum value returned by rand This macro expands to an integral constant expression whose value is the maximum value returned by the rand function.

This value is library-dependent, but is guaranteed to be at least 32767 on any standard library implementation.

Community
  • 1
  • 1
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
0

To generate a random number between min and max, and they should be long data type use:

long randamNum = rand()%(max-min + 1) + min;

(Includes max and min)

For more clearity refer Generating random integer from a range

Community
  • 1
  • 1
SSP
  • 2,650
  • 5
  • 31
  • 49
  • I'll bet you `sizeof(long) == sizeof(int)` for the OP. 16-bit ints aren't that common anymore and I have yet to know of something with 64-bit one but not the other. – chris Nov 01 '13 at 04:18
  • lol, no. An `int` can contain that number. That's not the problem. – Shoe Nov 01 '13 at 04:18
  • I can't see how type `long` or even `long long` will change anything – Bryan Chen Nov 01 '13 at 04:24