-2

I want to create some specific random, such that from 10 to 20.

rand()%20;

is create from 0 to 19

Justin Meiners
  • 10,754
  • 6
  • 50
  • 92
MrBoolean
  • 29
  • 6

1 Answers1

0

Apply some simple arithmetic

int val = min + (rand() % range);

Where range is (max - min) + 1

A random number betweeen 10-20 is just a random number between 0-10 shifted +10

Justin Meiners
  • 10,754
  • 6
  • 50
  • 92
  • 1
    Modulo division is not the best idea from the perspective of uniformity of resulting distribution. – void_ptr Oct 24 '15 at 00:17
  • @void_ptr True, but this works fine for most uses. – Justin Meiners Oct 24 '15 at 00:20
  • @chux Good catch. Thanks – Justin Meiners Oct 24 '15 at 00:21
  • @JustinMeiners and its this attitude which is why software has so much bugs. –  Oct 24 '15 at 00:22
  • @void_ptr can you tell us better way of doing this instead of modulo? I am not trying to offend you or get you upset, just want to learn something new. If you are not learning your are not living, you are dead :) –  Oct 24 '15 at 00:22
  • @EdgarAroutiounian It's not like the method is broken in a few cases - just not as mathematically precise. See chux reference. – Justin Meiners Oct 24 '15 at 00:24
  • @JustinMeiners thank you so much – MrBoolean Oct 24 '15 at 00:25
  • 1
    Ref: http://stackoverflow.com/a/11766794/2410359 – chux - Reinstate Monica Oct 24 '15 at 00:27
  • @GRC - No worries. From the uniformity perspective, the better way is to divide rand() result so as to make it fit the target range. Then again, wherever rand() suffices, things like minor uniformity discrepancy don't matter as much. Anyhow, linked answers cover it all better than I can explain here. – void_ptr Oct 24 '15 at 01:40