簡體   English   中英

C ++程序不會在循環時退出

[英]C++ Program will not exit while loop

當用戶輸入“ Q”或“ q”退出程序時,我的C ++程序不會在下面的循環中退出。 前兩個選項可以正常工作並調用其適當的函數,但是“退出程序”選項只是無限期地開始while循環。

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

int main()
{
    char choice; //Varible to hold the user's choice.

    while (choice != 'Q' || choice != 'q')
    {
        //Display the menu and retrieve the user's choice.
        cout << "Please choose from one of the options below:\n\n";
        cout << "A. Calculate the total amount of your bill [Enter A]\n";
        cout << "B. Calculate your BMI [ENTER B]\n";
        cout << "Q. Quit the program [Enter Q]\n\n";
        cout << "Enter your choice: ";
        cin >> choice;

        //Either calculate the user's bill or their BMI based on their choice.
        if (choice == 'A' || choice == 'a')
        {
            caLculateBillAmount();
        }
        else if (choice == 'B' || choice == 'b')
        {
            calculateBMI();
        }
    }

    return 0;
}

您應該簡單地使用while (choice !='Q' && choice !='q') {...} 是的,您應該將choice初始化為不同於“ Q”和“ q”的內容。 就像執行char choice=0;

問問自己以下內容的評估結果:

choice != 'Q' || choice != 'q'

如果選擇為“ Q”,則選擇不是“ q”,因此測試的右半部分為真。

如果選擇為“ q”,則選擇不是“ Q”,因此測試的左半部分為真。

您需要使用&&代替||,或者可以簡單地使用toupper(choice)!='Q'。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM