为什么这样做 - 虽然只接受pLife条件?

时间:2014-05-05 17:14:14

标签: c++ while-loop do-while

循环的唯一方法是当玩家用完生命时。该游戏应该允许玩家回答数学问题,他们回答直到他们或魔术师的生命。所以在do while循环中,while只在pLife耗尽时才起作用,完全忽略了eLife,为什么呢?

do 
{
    int Number = rand() % 20 + 1;       //Desides the random number that will be used in the program
    int aNumber = rand() % 20 + 1;
    int rng = rand() % 3 + 1;
    cout <<"Player Life Total = " <<pLife <<endl;
    cout <<"Mathmagican Life Total = " <<eLife <<endl;

    if (rng == 1)
    {
        cout <<"What is " <<Number <<"X" << aNumber <<"?\n\n";
        cin >> answer;
            if (answer == Number * aNumber)
            {
                cout <<"What!!! How is that possible you deflected my attack!\n\n";
                cout <<"Ahh it hit me!! you hit me with my own magic! Thats not fair!\n\n";
                eLife = eLife- 1;
            }
            else if (answer > Number * aNumber, answer < Number * aNumber)
            {
                cout <<"I told you that you couldn't defeat me!\n\n";
                cout <<"Now die!";
                pLife = pLife - 1;
            }
    }
    else if (rng == 2)
    {
        cout <<"What is " <<Number <<"-" << aNumber <<"?\n\n";
        cin >> answer;
            if (answer == Number - aNumber)
            {
                cout <<"What!!! How is that possible you deflected my attack!\n\n";
                cout <<"Ahh it hit me!! you hit me with my own magic! Thats not fair!\n\n";
                eLife = eLife- 1;
            }
            else if (answer > Number - aNumber, answer < Number - aNumber)
            {
                cout <<"I told you that you couldn't defeat me!\n\n";
                cout <<"Now die!";
                pLife = pLife - 1;
            }
    }
    else if (rng == 3)
    {
        cout <<"What is " <<Number <<"+" << aNumber <<"?\n\n";
        cin >> answer;
            if (answer == Number + aNumber)
            {
                cout <<"What!!! How is that possible you deflected my attack!\n\n";
                cout <<"Ahh it hit me!! you hit me with my own magic! Thats not fair!\n\n";
                eLife = eLife- 1;
            }
            else if (answer > Number + aNumber, answer < Number + aNumber)
            {
                cout <<"I told you that you couldn't defeat me!\n\n";
                cout <<"Now die!";
                pLife = pLife - 1;
            }
    }
}while (eLife > 0, pLife > 0);  

    if (eLife == 0)
    {
        cout <<"Oh no! I cant belive it... you... actualy... defeated me?!\n\n";
        cout <<"NO!!! CURSE YOU!!!";
        cout <<"You've Won!\n\n";
        system ("pause");
        return 0;
    }
    else if (pLife == 0)
    {
        cout <<"MWAHAHAHAHAHA!!!!! I told you i would win!\n\n";
        cout <<"Game over";
        system ("pause");
        return 0;
    }

}

1 个答案:

答案 0 :(得分:2)

将评估逗号分隔表达式中的每个单独表达式,并且将发生它们的副作用。但是,整个逗号分隔表达式的值只是最右边表达式的结果。因此,只有pLife > 0返回true时,while条件才会计算为true。

要解决此问题,请使用布尔运算符(例如&&||

将其更改为单个表达式