Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

c++ - Why is the || operator not triggered here?

int main()
{
    int precision = 10;
    int choice;

    //Title and Menu
    cout << endl << "==============" << endl << " TRIGONOMETRY " << endl << "==============";
    cout << endl << "Current Precision: " << precision;
    cout << endl << endl << "Select:";
    cout << endl << "1. Calculate Cos and Sin";
    cout << endl << "8. Change Precision";
    cout << endl << "9. Exit";

    while (true)
    {
        //User Prompt
        cout << endl << endl << "Please enter your choice. => ";
        cin >> choice;
        
        if (choice != 1 || choice != 8 || choice != 9)
            {
                cout << endl <<  "Please enter a value between 1, 8 and 9.";
            }  

        if (choice == 8)
            {
                cout << endl << "Current Precision: " << precision;
                cout << endl << "Please enter your desired precision => ";
                cin >> precision;
                cout << endl << "Precision has been set to " << precision;
            }

        if (choice == 9)
            {
                break;
            }
    }   
}

The idea is that if the user inputs something other than 1, 8 or 9 the program will print the line, but when I supposedly fulfilled the condition by inputting 4, 5, etc., the program jumps back to the main function without printing the line. Any ideas?

Thanks in advance.

Edit: I have since edited the condition for the first if loop to (choice != 1 && choice != 8 && choice != 9), but another problem now is that the program doesn't print the line when I input any non-1, 8, 9 numbers. I omitted the if loop for (choice == 1) cause it's too long and it might hinder reading.

question from:https://stackoverflow.com/questions/65646984/why-is-the-operator-not-triggered-here

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use the And operator (&&) to achieve the result that you want, try this:

if (choice != 1 && choice != 8 && choice != 9)
   {
      cout << endl << "Please enter a valid choice between 1, 8 and 9.";
   }

The reason why it didn't work with the Or operator (||) is because that for each number among 1, 8 or 9, your condition will always remains as true.
(For example: If choice = 1, choice != 1 might return false but choice != 8 will return true).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...