Thread: generate a random number

1. generate a random number

hi all,

i need to know how to generate a number..influenced by percentages..

how do u write code ...so for example, there is a 95% chance that a variable = 1 and the other 5% of the time it equals 0...

right now i got

#include <cstdio>
int random = rand () % 2;

but this is randomly giving me 1 or 0...

thanks.

2. Well for a percentage, you need rand() % 100

So to get to where you want to be
int random = rand() % 100 > 95 ? 1 : 0;

3. Why do more people use rand than
Code:
`random(int);`
.

4. Because rand() is a standard function, and random() isn't

5. random number with probabilities

Hi, just a follow up question to this thread. So how would you write the code if you have 3 numbers, for example, 60% probability of generating 0, 35% generating 1 and 5% generating 2. Thanks a lot

6. Code:
```int random = rand()%100;
int result;

if(random < 60)

result = 0;

else if(random >= 60 && < 95)

result = 1;

else

result = 2;```

Popular pages Recent additions