【发布时间】:2012-05-17 14:01:30
【问题描述】:
我为我的 C++ 类编写了这个函数,我尝试了 x = 4,但是当我跟踪它时,我没有看到它像应有的那样循环。它所做的是获取一个包含 5 个数字的数组并对它们进行排序,然后检查该组合是否构成满堂彩。
bool isFullHouse(int)
{
int match = 0;
BubbleSort(DiceHeld, 5);
for ( int x=0; x <= 4; x++ )
{
if (((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+2) && (DiceHeld[4] == x+2) && (DiceHeld[5] == x+2)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+1) && (DiceHeld[4] == x+2) && (DiceHeld[5] == x+2)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+3) && (DiceHeld[4] == x+3) && (DiceHeld[5] == x+3)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+1) && (DiceHeld[4] == x+3) && (DiceHeld[5] == x+3)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+4) && (DiceHeld[4] == x+4) && (DiceHeld[5] == x+4)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+1) && (DiceHeld[4] == x+4) && (DiceHeld[5] == x+4)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+5) && (DiceHeld[4] == x+5) && (DiceHeld[5] == x+5)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+6) && (DiceHeld[4] == x+2) && (DiceHeld[5] == x+2)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+6) && (DiceHeld[4] == x+6) && (DiceHeld[5] == x+6)) ||
((DiceHeld[1] == x+1) && (DiceHeld[2] == x+1) && (DiceHeld[3] == x+1) && (DiceHeld[4] == x+6) && (DiceHeld[5] == x+6)))
{
match = 1;
}
}
if (match == 1)
{
return true;
}
else
{
return false;
}
}
【问题讨论】:
-
它没有像它应该的那样循环?它的循环与您的预期有何不同?
-
我不能评论那个循环的 contents -- oy -- 但循环本身看起来不错,应该迭代五次。
-
您确定索引正确吗?您说您有 5 个数字的数组,但您使用的是 DiceHeld[5],它是数组的第六个元素。
-
您是否正在编译优化?我可以很容易地看到
match == 1测试被优化为break以便它提前停止...... -
计算每个数字出现的次数要简单得多,然后您可以检查某个数字出现了两次,而另一些数字出现了 3 次。等效地,您可以检查每个数字出现 0、2 或 3 次,或者没有数字出现 1、4 或 5 次。