为什么它只计算函数的第一行而不是其余的?

时间:2015-01-27 20:38:31

标签: c++ function

#include <iostream>
#include <string>
#include <regex>


using namespace std;

/*
Function Name: weightConv
Purpose: To take the weight and convert the following number to the coressponding weight unit
Return : 0
*/
  double weightConv(double w, string weightUnit)
{
     if (weightUnit == "g" , "G" )
        cout << " Mass = " <<  w * 0.035274 << "oz";
    else if (weightUnit == "oz", "OZ", "oZ" , "Oz")
        cout << " Mass = " <<  w / 28.3495 << "g";
    else if (weightUnit == "kg", "KG", "Kg" , "kG")
        cout << " Mass = " <<  w * 2.20462 << "lb";
    else if (weightUnit == "lb" , "LB" , "Lb" , "lB")
        cout << " Mass = " <<  w / 0.453592 << "kg";
    else if (weightUnit == "Long tn" , "LONG TN")
        cout << " Mass = " <<  w * 1.12 << "sh tn";
    else if (weightUnit == "sh tn" , "SH TN")
        cout << " Mass = " << w / 0.892857 << " Long tons";
    else
        cout << "Invalid unit of measurement";

    return 0;
}// end of weightCov function


int main()
{
    for (;;)
    {

        double mass;
        string unitType;
        cout << "Enter a mass and its unit type indicator(g,kg,lb,oz,long tn,or sh tn)" << endl;
        cin >> mass >> unitType;


        // case insensitive strings
        //regex reg_icase("g", regex::icase);
        //if (regex_match("G", reg_icase))

            // Output Results
            cout << weightConv(mass, unitType) << endl;

    }// end of for loop
}// end of main 

当我输入一个数字和相应的权重单位时,它只会执行if语句的weightConv函数的第一行,即使我要做25kg它仍然会返回“oz”而不是“lb”。谁能解释一下?

3 个答案:

答案 0 :(得分:2)

if (weightUnit == "g" , "G" )表示if ("G" )始终为真。您需要做的是使用或运算符||。看起来像是:

if (weightUnit == "g" || weightUnit == "G" )

其他if语句也是如此。

答案 1 :(得分:0)

你可能打算写

if ((weightUnit == "g") || (weightUnit == "G"))

而不是

  

if (weightUnit == "g" , "G" )

在对"G"进行测试时,逗号运算符将始终生成weightUnit

另一种方法是

if (!weightUnit.empty() && (std::tolower(weightUnit[0]) == `g`))

答案 2 :(得分:0)

将所有if语句更改为:

if (weightunit == "g" || weightunit == "G")

等等。问题是你的陈述正在做的是首先计算weightunit == "g"的结果,然后计算"G"的结果。在C / C ++中,所有既不为零也不是bool且值为false的语句都被认为是真的,并且&#34; G&#34;是存储字符数组的指针地址,它不是零,因此它的计算结果为真。