-1

我为我的 C++ 类编写了这个函数,我尝试了 x <= 4 并且也尝试了 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;
        }
    }
4

2 回答 2

1

您的索引DiceHeld应该可能从 0 到 4。根据您的编译器和调试器,内存错误可能不明显,但仍然会发生。

我还敢打赌,match退出循环后它不是 1。

于 2012-05-17T14:24:07.930 回答
1

为了好玩,这是一个不需要如此繁重的逻辑或排序的版本:



static const int kNumDice = 5;

bool isFullHouse()
{
    // There are only 2 possible patterns for full house on a set of numbers, sorted or not
    // Either the first 3 dice have the same value and the 4th and 5th dice are the same
    // or the first 2 dice match and the 3rd, 4th, 5th dice match 

    int currentMatch = DiceHeld[0];
    int uniqueValues = 1;
    int matchLength = 1;

    for(int i=1; i<kNumDice; i++)
    {
        // Start next match
        if(DiceHeld[i] != currentMatch)
        {
            if(matchLength < 2)
            {
                return false; 
            }

            if(++uniqueValues > 2)
            {
                return false;
            }

            currentMatch = DiceHeld[i];
            matchLength = 1;
        }
        else if(++matchLength > 3)
        {
            return false;
        }
    }

    return true;
}
于 2012-05-17T15:11:55.690 回答