如果在c++中有语句,那就大错特错了

If statement in c++, freaks out

本文关键字:错了 c++ 语句 如果      更新时间:2023-10-16

当我试图运行这个游戏,并想通过键入"slut"或"slut"(瑞典语中"end"的意思)来结束它时,当我在while循环或If语句中只有一个语句时,它会让一个新玩家称之为"slut"或"slut"一切正常。更清楚地说,当我有(playerName!="荡妇")但为了安全起见,我有(playerCame!="Slut")||(playerName!="Slut")时它就工作了,然后它就不工作了。

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

int main(){

//Declaration
setlocale(LC_ALL, "Swedish");           //Swedish characters
int dices;
int diceSum = 0;
int absoluteLowestSum = 999999999;      //To get out the lowest sum I'm comparing to a big value
int diceRoll1 = 0;
int diceRoll2 = 0;
string playerName;
string playerLost;
//Plants a seed
srand((int)time(0));
//Instructions
cout << "Nu spelar vi ”Otur i tärning”: " << endl;
cout << "Hur många tärningskast ska göras per spelare?" << endl;
cin >> dices;

//If "slut"/""Slut" is written, while stops
while ((playerName != "Slut") || (playerName != "slut")){
    cout << "Namnet på spelaren?";
    cin >> playerName;
    for (int i = 0; i < dices; i++){
        if ((playerName != "Slut") || (playerName != "slut")){
            diceRoll1 = rand() % 6 + 1;
            diceRoll2 = rand() % 6 + 1;
            cout << diceRoll1 << " " << diceRoll2 << " = " << diceRoll1 + diceRoll2 << endl;
            diceSum = diceSum + diceRoll1 + diceRoll2;


        }
    }
    if ((playerName != "Slut") || (playerName != "slut")){

        while (diceSum < absoluteLowestSum){        //Give us the lowest sum
            absoluteLowestSum = diceSum;
            playerLost = playerName;                    //Give us the name who lost
        }
        cout << "Summan: " << diceSum << endl;
        diceSum = 0;                                //Puts the sum to 0 when a new player enters his/her name
    }
    if ((playerName == "Slut") || (playerName == "slut")){

        cout << playerLost << " hade mest otur och fick tärningssumman " << absoluteLowestSum << endl;
    }

}


return 0;

}

您必须使用&&而不是||。它应该是

if ((playerName != "Slut") && (playerName != "slut")) 

while ((playerName != "Slut") && (playerName != "slut"))

在所有具有!=playerName != "Slut"playerName != "slut")的ifs和while条件下