无论这里生成什么数字,我总是得到第一个选项(企鹅)。我似乎看不出我的代码有任何问题,其他人看到了什么问题吗?
{
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
是一个表达式序列(,
通常称为逗号运算符),其中第一个(或最后一个 — 取决于语言)表达式的结果 only 用作if
语句的条件。对剩余的表达式求值并忘记它们的值(请注意,这可能会在更复杂的情况下导致严重的副作用。)
不太清楚您使用的是什么语言,但是在 C# 中,您可以使用 switch statement实现你想要的:
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;
}
大多数语言都有这样的声明。看这个wikipedia article以获得一般描述。
关于c++ - if 语句中的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16281125/