如果语句运行即使不是真的

时间:2015-08-15 12:19:26

标签: c++

我不确定我在这里做错了什么,每次运行它都会经过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;
}

2 个答案:

答案 0 :(得分:2)

&#39;如果&#39;的语法有问题?声明。以下是更正后的代码,其中&#39; ||&#39;代表&#39;或&#39;:

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

答案 1 :(得分:0)

更改此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