# C++ and Probablities!

1. Mar 12, 2013

### Tenshou

I am not sure how to assign probabilities to variables do you think you guys will be able to help me?

2. Mar 12, 2013

Can you be more specific? Do you know how to assign probabilities on paper? If so, it shouldn't be too hard to translate your paperwork into source code.

3. Mar 12, 2013

### Tenshou

No, I mean how do you give a variable a probability, for example, in a conditional statement you will printf(hello world) when the probablity is 1/3 or you will printf(Good Day!) if the probability is 1/3 or printf(Good Bye) if the probability is 1/3. What I mean is how will I get a conditional statement to run as if they were probablities... would I just conjoin it with if, else ,when statements?

4. Mar 12, 2013

I don't use C++, but you can generate a random number and then decide on a course of action depending on the result. For example:

Code (Text):
#include <stdlib.h> // C standard library
float num = rand() % 9; // this is the C rand function, and your number will be between 0-8

if (num < 3)
{
// do something
}
else if (num >= 3 && num <= 6)
{
// do something else
}
else // implication num > 6 && num <= 8
{
// do something else
}
Your random number will be in one of the 3 ranges with 1/3 probability, although it's worth noting that rand() is a pseudo-random number generator, but it's probably fine for your purposes.

5. Mar 12, 2013

### Tenshou

Thank you! How would you make this loop keep going with out terminating?

6. Mar 12, 2013

### Staff: Mentor

Do you know how to make a loop that does terminate? Simply use a loop condition that never becomes 'false'.

7. Mar 12, 2013

### Staff: Mentor

What Adyssa wrote is NOT a loop; it's an if...else block. To make this a loop, you would need to embed the if-else block in a loop of some kind.

8. Mar 12, 2013

### Tenshou

when I said "when statement" I meant to say while sorry >.< so I would make a bool variable and have it always true while the conditional is looping or something of that fashion?

9. Mar 12, 2013

### AlephZero

Correct, but you don't need to use a variable. This is usually written as
Code (Text):

while (true) {
// do something
}

The "do something" code probably needs to contain a "break" statement somewhere, unless you really want the program to run for ever!

10. Mar 12, 2013

### Staff: Mentor

You could do something like this:
Code (Text):

while (1)
{
Get a random number (in the range 0 .. RAND_MAX)
Turn it into a probability by dividing by RAND_MAX
if (prob < .3333)
{
do something
}
else if (prob < .6666)
{
do something else
}
else
{
do the third thing
}
}