0

我编写了一段似乎无法按要求工作的代码:

typedef enum{none=0,apple,grape,orange} FRUIT;

FRUIT first = rand()%4;
FRUIT second = rand()%4;
FRUIT third = rand()%4;

所以在我的条件下,我可以拥有

if (first == (none | apple | grape | orange) &&
    second == apple &&
    third == (none | apple | grape | orange)
{
    cout<<"Here"<<<endl;
}

变量firstthird可以具有任何applegrapenoneorange值。那么 if 条件是否正确?我没有得到想要的输出,因为它根本没有进入 if 条件。

4

2 回答 2

3

在条件:

first == (none | apple | grape | orange)

您应该使用逻辑或 ( ||) 而不是按位或 ( |)。不幸的是,即使您将其更改为:

first == (none || apple || grape || orange)

将首先评估此条件的右侧,使其(在这种情况下)等效于:

first == true

这在语义上仍然与您可能的意思不同:

first == none || first == apple || first == grape || first == orange

另请注意,rand()在这里使用不是很明智。您可以尝试std::random_shuffle改用:

FRUIT fruit[] = { none, apple, grape, orange,
                  none, apple, grape, orange,
                  none, apple, grape, orange};
srand(time(NULL));
std::random_shuffle(&fruit[0], &fruit[11]);
FRUIT first = fruit[0];
FRUIT second = fruit[1];
FRUIT third = fruit[2];

只是不要忘记#include <algorithm>:)

于 2013-09-22T01:03:41.717 回答
0

我是否正确地将枚举值与 C++ 的“或”运算符进行比较?

不,你需要写:

first == none || first == apple || first == grape || first == orange
于 2013-09-22T10:31:59.967 回答