警告 C6236:( || ) 始终是非零常量

oXe*_*eru 1 c++ if-statement visual-studio

我有一个似乎根本不起作用的 if 语句。我确定这是一个愚蠢的错误,但我无法弄清楚。

void convertTemp()
{
    char choice;
    float userTemp;
    cout << "Input either F or C followed by a temperature and this program will convert it to the opposite." << endl;
    cout << "Example: (F 260.8)" << endl;
    cout << "Input: ";
    cin >> choice; choice = toupper(choice); //Read in and convert user letter to capital 
    cin >> userTemp;

    if (choice != 'F' || 'C')
    {
        cout << "Invalid format. Check your letter and temperature" << endl;
        system("pause");
        return;
    }
Run Code Online (Sandbox Code Playgroud)

这个简单的 if 语句旨在检查用户输入的字符是否不是“F”或“C”,然后返回一条错误消息并将它们踢出函数。但是,无论输入如何,这个 if 语句总是返回 true,我不知道为什么。任何帮助将不胜感激!

Visual Studio 给我这个警告信息。我阅读了错误代码,但我很难理解它。

警告 C6236:( || ) 始终是非零常量

Aus*_*tin 5

你的if陈述需要明确,if (choice != 'F' || 'C')行不通的。

正确的if说法是if (choice != 'F' && choice != 'C')

编辑:至于解释,这||意味着您有两个正在评估的语句。在英文中,该声明可以读为:

IF the choice is not 'F' or IF 'C'

……这真的没有意义。您需要明确声明您希望双方评估选择是否等于值。

还要感谢 Pete Becker,我复制并粘贴了您的问题,而没有真正深入研究您所做的事情背后的逻辑。如果您尝试使用ORwith !=,一半几乎总是评估为真。Using&&是您想要的运算符,因此您可以检查是否choice不是CF