0
\$\begingroup\$

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)?

\$\endgroup\$
3

1 Answer 1

2
\$\begingroup\$

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.

\$\endgroup\$
2
  • 4
    \$\begingroup\$ 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) { ... }. \$\endgroup\$
    – Anko
    Commented Aug 8, 2014 at 16:26
  • \$\begingroup\$ Ok, I didn't thought about that. I will edit my answer. \$\endgroup\$ Commented Aug 8, 2014 at 17:22

Not the answer you're looking for? Browse other questions tagged .