if语句中的多个条件 [英] Multiple conditions in if statement
问题描述
无论这里生成什么数字,我总是得到第一个选项(企鹅).我的代码似乎看不到任何问题,其他人看到了什么问题吗?
No matter what number is generated here I always get the first option (penguins). I can't seem to see any problem with my code, anyone else see what's wrong?
{
srand(time(0));
prand = (rand() % 20);
if (prand == 1,5,9,10,14,15,19,20){
entity = "penguins";
srand(time(0));
pquantity = (rand() % 8) + 2;
}
else if (prand == 2,6,11,16,18){
entity = "troll";
pquantity = 1;
}
else if (prand == 3,7,12,17){
entity = "goblin";
pquantity = 1;
}
else if (prand == 4,8,13){
entity = "wizard";
pquantity = 1;
}
}
推荐答案
代码片段 prand == 1,5,9,10,14,15,19,20
是表达式序列(,
通常称为逗号运算符),其中 first (或 last (取决于语言))仅将 表达式用作 if
语句的条件.对其余的表达式进行评估,并忘记它们的值(请注意,在更复杂的情况下,这可能会导致严重的副作用.)
The code fragment prand == 1,5,9,10,14,15,19,20
is a sequence of expressions (the ,
is usually know as the comma operator), where the result of the first (or last — depending on language) expression only is used as a condition for the if
statement. The remaining expressions are evaluated and their value is forgotten (please note this may lead to serious side effects in more complex situations.)
尚不清楚您使用的是哪种语言,但是在C#中,您可以使用切换语句以实现所需的内容:
It's not very clear what language you are using, but in, say, C# you could use a switch statement to achieve what you want:
switch (prand)
{
// first set of options
case 1:
case 5:
…
case 20:
// your code here
break;
// second set of options
case 2:
case 6:
…
case 18:
// your code here
break;
default:
// all other options not listed above
break;
}
大多数语言都有这样的陈述.有关一般说明,请参见此维基百科文章.
Most languages have such a statement. See this wikipedia article for a general description.
这篇关于if语句中的多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!