# generate a random number

• 06-03-2005
waxydock
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.
• 06-03-2005
Salem
Well for a percentage, you need rand() % 100

So to get to where you want to be
int random = rand() % 100 > 95 ? 1 : 0;
• 06-03-2005
arjunajay
Why do more people use rand than
Code:

`random(int);`
.
• 06-03-2005
Salem
Because rand() is a standard function, and random() isn't
• 06-05-2005
Verbenaca
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:)
• 06-05-2005
The Brain
Code:

```int random = rand()%100; int result; if(random < 60)     result = 0; else if(random >= 60 && < 95)     result = 1; else     result = 2;```