Would this produce a 1/10 chance that action A is played?
float ran = random(10);
if (ran == 2)
{
//action A
}
else if (ran != 2)
{
//action B
}
Would this produce a 1/10 chance that action A is played?
float ran = random(10);
if (ran == 2)
{
//action A
}
else if (ran != 2)
{
//action B
}
random() returns a float
datatype value: Processing.org/reference/random_.html
You need an int
instead:
final int choice = (int) random(10); // range 0 to 9
if (choice == 2) {
}
else {
}
Would this also work?
int ran = (int)random(10);
Then I would be able to keep my previous code
if (ran == 2)
{
//action A
}
else if (ran != 2)
{
//action B
}
Yes, it would. You donāt need the if(ran != 2)
bit thoughājust the else
will do. This is because the else bit only runs if the if stuff before hasnāt run.
Yes, it would alright!
That Would work too, since it means the Same. But the second if (ran != 2) is obsolete. If it is 2, then the if (ran == 2) is true, Else the other one is. What you are doing is just adding a redundant condition. You can do it, But itās better to not, performance wise. (Doesnāt matter much now, But it stacks if you do it this way some Million Times.
Keep in mind that one of the most basic ways to inspect whether in code is doing what you want is to test it.
So, you can answer your question by like this:
float ran = random(10);
println(ran);
7.702701
Or try printing a sample of outputs:
for (int i=0; i<10; i++) {
println(random(10));
}
8.375377 5.7671003 0.24511933 1.3771093 6.604124 3.733101 2.9731035 2.9664493 5.653407 4.418477
ā¦and, if you are unsure (maybe 7.7 == 7, or 8?), try it!
if (7.702701 == 7) {
println("true");
}
if (7.702701 == 8) {
println("true");
}
You will notice that warnings pop up in the PDE error box ādead codeā ā those will never be true.