在while循环中接受用户输入

时间:2012-11-12 17:52:03

标签: c++ while-loop user-input

我正在尝试创建一个简单的温度转换程序,允许用户根据需要多次转换温度,直到他们决定通过输入字母“e”来结束程序。除了用户输入字母“e”的部分外,代码中的其他所有内容都有效。如果我取出最后一个else语句,程序就会再次从循环开始处开始。如果我留下else语句,当用户输入字母'e'时,else语句认为它是无效输入并且不会结束程序。

 #include <iostream>

using namespace std;

float celsiusConversion(float cel){     // Calculate celsius conversion
    float f;

    f = cel * 9/5 + 32;
    return f;
}

float fahrenheitConversion(float fah){  // Calculate fahrenheit conversion
    float c;

    c = (fah - 32) * 5/9;
    return c;

}
int main()
{
    char userInput;

        while (userInput != 'e' or userInput != 'E')    // Loop until user enters the letter e
        {

            cout << "Please press c to convert from Celsius or f to convert from Fahrenheit. Press e to end program." << endl;
            cin >> userInput;


            if (userInput == 'c' or userInput == 'C') // Preform celsius calculation based on user input 
                {
                    float cel;
                    cout << "Please enter the Celsius temperature" << endl;
                    cin >> cel;
                    cout << cel << " Celsius is " << celsiusConversion(cel) <<  " fahrenheit" << endl;
                }
            else if (userInput == 'f' or userInput == 'F')  // Preform fahrenheit calculation based on user input
                {
                    float fah;
                    cout << "Please enter the Fahrenheit temperature" << endl;
                    cin >> fah;
                    cout << fah << " Fahrenheit is " << fahrenheitConversion(fah) << " celsius" << endl;
                }
            else    // If user input is neither c or f or e, end program
                {
                    cout << "Invalid entry. Please press c to convert from Celsius, f to convert from Fahrenheit, or e to end program." << endl;
                }
        }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

你的意思是while(userInput != 'e' && userInput != 'E')

'或'版本始终为真

答案 1 :(得分:0)

我会对您的代码进行2次更改:

while (userInput != 'e' && userInput != 'E')

并且,就在“else”之前(为了防止退出程序时出现错误消息):

else if (userInput == 'e' or userInput == 'E')
             {
                break;
             }
相关问题