1

Type two statements that use rand() to print 2 random integers between (and including) 100 and 149. End with a newline. Ex:

101
133

I've tried...

cout << rand() % 100 << endl;
cout << rand() % 149 << endl;

...and can't get it to work.

I'm super confused. Any help would be appreciated!

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 1
    `(rand() % 49) + 100`? – Marc B Aug 29 '14 at 16:28
  • 3
    `(rand() % 50) + 100` should be better, considering the including. – Jason Hu Aug 29 '14 at 16:38
  • Nevermind! Figured it out! Here's to anyone else that comes across this problem in confusion. cout << rand((149 - 100 + 1) + 100) cout << rand((149 - 100 + 1) + 100) Just type the statement twice, without change, and success!! Here's the format: n1=100 n2=149 cout << rand((n2 - n1 + 1) + n1) cout << rand((n2 - n1 + 1) + n1) – Austin Coleman Head Aug 29 '14 at 20:27
  • @AustinColemanHead : what is this `rand()` with arguments ? Also note that `rand((149 - 100 + 1) + 100)` == `rand(150)` .. – quantdev Aug 29 '14 at 21:23

1 Answers1

5

Don't use (rand() % 50) + 100 if you want a uniform distribution.

Use std::uniform_int_distribution from the <random> header :

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(100, 149);

    for (int n=0; n<2; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

Live demo

quantdev
  • 23,517
  • 5
  • 55
  • 88