C ++ If / Else语句被跳过

时间:2018-10-21 16:37:34

标签: c++ if-statement

我正在写一个Craps程序作为学校作业。在此代码中,无论掷骰子是什么,程序都会跳过所有“ if”块,并继续经过此代码段的最后一行。随机数生成器设置为仅生成数字1-12,因此每次返回都在该范围内。

int diceRoll = ThrowDice();

if (diceRoll == '7' || diceRoll == '11')
{
    cout << "\nCongratulations! You won!!";
    didWin = true;
    UpdateBalance(didWin, bet);
}
else if (diceRoll == '2' || diceRoll == '3' || diceRoll == '12')
{
    cout << "\nYou lose!";
    didWin = false;
    UpdateBalance(didWin, bet);
}
else if (diceRoll == '1' || diceRoll == '4' || diceRoll == '5' || diceRoll == '6' || diceRoll == '8' || diceRoll == '9' || diceRoll == '10')
{
    int diceRollPoint = PlayPointRound(diceRoll);
    if (diceRollPoint == '7')
    {
        cout << "\n\nSorry, you lose!";
        didWin = false;
        UpdateBalance(didWin, bet);
    }
    else if (diceRollPoint == diceRoll)
    {
        cout << "\n\nYou won!!!";
        didWin = true;
        UpdateBalance(didWin, bet);
    }
}

2 个答案:

答案 0 :(得分:1)

您的骰子掷骰表示为int,但是您正在将它们与char文字进行比较。您应该通过删除引号来使用int文字。例如:

int diceRoll = ThrowDice();
if (diceRoll == 7 || diceRoll == 11) {
    // Here ----^----------------^

答案 1 :(得分:1)

'7'的含义与写7的含义不同。

前者是一个字符文字,可以理解为对应于该字符的整数代码,另一个只是整数7。