0
\$\begingroup\$

This question already has an answer here:

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\$

marked as duplicate by Anko, Josh Aug 8 '14 at 16:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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\$
  • 3
    \$\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 Aug 8 '14 at 16:26
  • \$\begingroup\$ Ok, I didn't thought about that. I will edit my answer. \$\endgroup\$ – user000user Aug 8 '14 at 17:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.