If statement in c++, freaks out [duplicate]

旧城冷巷雨未停 提交于 2019-12-31 07:39:26

问题


when I try to run this game and wants to end it by typing "slut" or "Slut" (Swedish for 'end') it makes a new player call "slut" or "Slut" BUT when I only have ONE statement in the while loops or If statements it's all working. To make it more clear It works when I have (playerName != "Slut") but I want for safty have (playerName != "Slut") || (playerName != "slut") and then it wont work.

#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;

}


回答1:


You have to use && instead of ||.Its supposed to be

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

And

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

in all the ifs and while conditions having != (playerName != "Slut" and playerName != "slut")



来源:https://stackoverflow.com/questions/25957807/if-statement-in-c-freaks-out

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!