Random Numbers between 1 and 20

#include <time.h>

int twenty_random_num(void)
{
srand(static_cast<unsigned int>(time(0)));

int num=rand();

num=(num%20)+1;/// For Making Numbers Between 1 and 20 !!!!

return num;
}
What's your question?

I guess it does not work, right?
That's because you should call srand only once, ideally at the beginning of your program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <ctime>
using std::cout;


int randRange (int low, int high)
{
    return rand() % (high - low) + low;
}

int main()
{
    srand(time(NULL));
    cout << randRange(1, 21);
}


That's how I do it. IMO it's a bit cleaner. If anyone wants to comment and tell me how I can improve, please go ahead. I'm farely new and all criticism is helpful!
Last edited on
Topic archived. No new replies allowed.