# How can I implement a percentage chance to perform some action? [duplicate]

Let's say that there is an X% chance that a character will shoot a target, or some other action. How do I determine if the action should be taken or not (how do I implement the percentage chance)?

## 1 Answer

One way to do this is, take a pseudo random generator and let it generate a float between 0 and 1. You would then multiply it with 100 to get into the range of 0 to 100. If this final value is smaller than the percent of the chance, in this example, the tank would hit the target. Here is some pseudo code, what it could look like:

// chance of tank, hitting the target
float chance = 70.0f;

// first, generate a pseudo random float in the range of 0 to 1
float n = random();

// multiply n with 100 to get into the range of 0 to 100
n = n * 100;

// if n is below chance, the tank will hit the target
if(n < chance)
{
// do something here
}


Edit: Changed from int to float, due to the fact that Anko mentioned.

• The modulo operator is often a really bad idea with random numbers. The maximum integer produced by random is in most cases not a multiple of 100, causing a biased output: Imagine if the maximum integer was 150. Everything from 0-100 would % 100 to the range 0-100. Everything from 101 to 150 would mod to 1-50. That means outputs 0-50 are much more likely! Instead, have your RNG generate a float and do if (randomFloat() * 100 < chance) { ... }.
– Anko
Aug 8, 2014 at 16:26
• Ok, I didn't thought about that. I will edit my answer. Aug 8, 2014 at 17:22