random number Question

1
2
srand(time(0);
cout << (rand()%19)+1;


how come this isn't producing random numbers between 1-20?
Last edited on
@InterFiction

When you call (rand()%19), it gives a random number from 0 to 18, nineteen numbers, so adding 1 only gives numbers 1 to 19. No number 20.
InterFiction wrote:
how come this isn't producing random numbers between 1-20?


Because your code

1
2
srand(time(0);
cout << (rand()%19)+1;


take away the parenthesis around rand()%20+1

and then make the first line srand(time(NULL));
Last edited on
That's helpful...but I'm getting numbers like 71..lol

I'll show the whole code in case there's something else wrong..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<cstdlib>
#include <ctime>

using namespace std;

int main()
{
    int BABA;

    while(BABA!=55){
    srand(time(0));

    cout << (rand()%20)+1;
    BABA = BABA + 1;
    }

    return 0;
}
Last edited on
make it rand()%20+1

it'll be numbers through 1-20 after adding the one.
You also did not initialize BABA with a value, so who knows what value it has to have a one added to it?
very true, lol. Thanks for pointing that out :).
Topic archived. No new replies allowed.