C++ 为什么它只计算函数的第一行而不计算其余的? #包括 #包括 #包括 使用名称空间std; /* 函数名称:weightConv 目的:取重量并将以下数字转换为堆芯重量单位 返回:0 */ 双重量转换(双w,字符串重量单位) { 如果(权重单位=“g”,“g”) cout

C++ 为什么它只计算函数的第一行而不计算其余的? #包括 #包括 #包括 使用名称空间std; /* 函数名称:weightConv 目的:取重量并将以下数字转换为堆芯重量单位 返回:0 */ 双重量转换(双w,字符串重量单位) { 如果(权重单位=“g”,“g”) cout,c++,function,C++,Function,if(weightUnit==“g”,“g”)的意思是if(“g”),这始终是真的。您需要做的是使用or运算符|。这看起来像: #include <iostream> #include <string> #include <regex> using namespace std; /* Function Name: weightConv Purpose: To take the weight and convert the following number

if(weightUnit==“g”,“g”)
的意思是
if(“g”)
,这始终是真的。您需要做的是使用or运算符
|
。这看起来像:

#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语句的其余部分也是如此。

您可能是有意编写的

if (weightUnit == "g" || weightUnit == "G" )
而不是

if(weightUnit==“g”,“g”)

逗号运算符将始终产生
“G”
,以测试
权重单位

另一种方法是

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

将所有if语句更改为:

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

以此类推。问题是,您的语句所做的是首先计算
weightunit==“g”
,然后计算
“g”
的结果。在C/C++中,所有既不是零也不是值为false的
bool
语句都被视为真,而值为“g”指针数组的地址是不是字符数组,它不是零,所以它计算真。

请查找C++文档,以得到逗号运算符。C++比较不这样工作。在IF语句中,你必须做:<代码> if(WebUng==G){WebUng==“G”)。
实际上,比较应该是:
if(toupper(weightUnit)='G')
if(tolower(weightUnit)='G')
对每个字母大小写进行比较是糟糕设计的标志。在比较之前,将字符串变量转换为所有小写或所有大写。在internet上搜索“c++transform toupper”。
if (weightunit == "g" || weightunit == "G")