我有一个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;
}
这个简单的if语句旨在检查用户字符输入是否不是'F'或'C',然后返回错误消息并将其踢出函数。但是,无论输入如何,此if语句始终返回true,我不知道为什么。任何帮助将不胜感激!
Visual Studio正在向我发出此警告消息。我读到有关错误代码的信息,但我很难理解它。
最佳答案
您的if
语句需要明确,if (choice != 'F' || 'C')
将不起作用。
正确的if
语句是if (choice != 'F' && choice != 'C')
。
编辑:作为一种解释,||
意味着您有两个正在评估的语句。用英语,该语句可以理解为:IF the choice is not 'F' or IF 'C'
...那真的没有道理。您需要明确声明,如果选择等于值,双方也要评估。
还要感谢皮特·贝克尔(Pete Becker),我复制并粘贴了您的问题,而没有真正深入研究您所做工作的逻辑。如果您尝试将OR
与!=
一起使用,则一半将总是评估为true。使用&&
是您想要的运算符,因此您可以检查choice
不是C
还是F
。
关于c++ - 警告C6236:(||)始终为非零常量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59568905/