Random number for 10 to 99

Nov 20, 2019 at 12:20am
The question was to generate a random number from 10 to 99, inclusive. I know enough to write the code below to generate 1 to 99. But is there any way to do just 10 to 99. I tried to look it up, but there was nothing helpful.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main (){
    srand(time(NULL));
    cout << (rand() % 98 + 1);

    return 0;
}
Nov 20, 2019 at 1:05am
Your code will generate a random number between 1 and 98, not 99.

If you have to use the antiquated, outdated and imperfect C library random functions:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <ctime>
#include <cstdlib>

int main()
{
   srand(time(NULL));

   std::cout << (rand() % 90 + 10) << '\n';
}


Modern C++ <random> library:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <random>

int main()
{
   // create a random engine, seeding it with a true random number
   std::default_random_engine eng(std::random_device {}());

   // create a uniform integer distribution, from 10 to 99 inclusive
   std::uniform_int_distribution<int> dis(10, 99);

   // generate a random number
   std::cout << dis(eng) << '\n';
}


http://www.cplusplus.com/reference/random/
Nov 20, 2019 at 4:05am
I think you should change this

cout << (rand() % 98 + 1)

to

cout << (rand() % 90 + 10)
Topic archived. No new replies allowed.