2

我正在尝试创建一个简单的温度转换程序,该程序允许用户根据需要多次转换温度,直到他们决定通过输入字母“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;
}
4

2 回答 2

1

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

'or' 版本总是正确的

于 2012-11-12T17:56:12.093 回答
0

我将对您的代码进行 2 处更改:

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

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

else if (userInput == 'e' or userInput == 'E')
             {
                break;
             }
于 2012-11-12T18:05:04.493 回答