If语句即使不为真也在运行

If statement running even when not true

本文关键字:运行 语句 If      更新时间:2023-10-16

我不确定我在这里做错了什么,每次我运行它,它通过if部分,即使它不是真的?所以'else'永远不会运行。

#include <iostream>
using namespace std;
string choice;
float numb;
float convert(float numb,string choice)
{
    float newNo;
    if (choice == "F" or "f"){
        newNo = numb * 0.2 * 9 + 32;
    }else{
        newNo = (numb - 32) / 1.8;
    }
    return newNo;
}
int main()
{
    cout << "welcome to Temperature converter v0.1" << endl;
    cout << endl;
    cout << "Which conversion would you like to use?" << endl;
    cout << "type C to convert to Celsius and F to convert to Fahrenheit - ";
    cin >> choice;
    cout << "what number would you like to convert? - ";
    cin >> numb;
    cout << convert(numb,choice);

    return 0;
}

问题是你的if声明:

if (choice == "F" or "f"){

基本上,你这里说的是:如果选择"F"或者"F"你需要明白:真是除了零之外的一切(0)。"f"不是零,所以它是正确的。你也可以这样写(or = ||):

if (coice == "F" || true)

相同
if (true)

所以为了让你的代码工作,你需要:

if (choice == "f" || choice == "F")

if语句语法有问题。以下是更正后的代码,其中'||'代表'或':

if ((choice == "F") || (choice=="f")){
    newNo = numb * 0.2 * 9 + 32;
}else{
    newNo = (numb - 32) / 1.8;
}

修改if语句

if (choice == "F" or "f"){

到下面的

if (choice == "F" or choice == "f"){

否则为or的右操作数

"f"

总是等于true,因为它被转换为字符串字面值的第一个字符的地址,该字符显然不等于0。

if语句中的原始条件就像

if (choice == "F" or "f" != nullptr){

"f" != nullptr