Quick question about rand()

closed account (10oTURfi)
All tutorials taught me how to specify max number generated by rand(), but how specify min number generated? For example, I do not want it to generate number 1.
you can't specify a minimum, rand() will always return a value between 0 and RAND_MAX. You can however manipulate the value it returns so if you wanted a number between 5 and 10 for instance

 
int randNum = rand()%6 + 5;

rand()%6 gives you a number between 0 and 5 and then you shift it towards the desired minimum by adding 5. You can do this to create a random number between whatever values you want, for a number between two values 'x' and 'y' given that y > x int randNum = rand()%(y-x+1) + x
Last edited on
closed account (10oTURfi)
Thanks alot.
I got one more question:
Is this valid way to make something have 1% chance of happening?

1
2
3
4
5
6
7
8
9
10
#include <time.h>
#include <cstdlib>

//...
srand(time(NULL));
num = rand() % 100+1;
if(num == 1)
    {
    //...
    }
Last edited on
probability says so, but practically it varies.
Topic archived. No new replies allowed.