为什么它在输出结束时字面上返回0

时间:2015-01-31 02:17:26

标签: c++

#include <iostream>
#include <string>



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" || weightUnit == "G" )
        cout << " Mass = " <<  w * 0.035274 << "oz";
    else if (weightUnit == "oz"||weightUnit == "OZ"||weightUnit == "oZ" ||weightUnit == "Oz")
        cout << " Mass = " <<  w * 28.3495 << "g";
    else if (weightUnit == "kg"||weightUnit == "KG"||weightUnit == "Kg" ||weightUnit == "kG")
        cout << " Mass = " <<  w * 2.20462 << "lb";
    else if (weightUnit == "lb" ||weightUnit == "LB" ||weightUnit== "Lb" ||weightUnit == "lB")
        cout << " Mass = " <<  w * 0.453592 << "kg";
    else if (weightUnit == "Long-tn" ||weightUnit == "LONG-TN"|| weightUnit == "long-tn" || weightUnit == "long-ton")
        cout << " Mass = " <<  w * 1.12 << "sh tn";
    else if (weightUnit == "sh-tn" || weightUnit == "SH-TN")
        cout << " Mass = " << w / 0.892857 << " Long tons";
    // one other converstion that was not listed in the project desription (stones<->tons)
    else if (weightUnit == "s" || weightUnit == "S")
        cout << " Mass = " << w * 0.007 << "tons";
    else if (weightUnit == "tons" || weightUnit == "Tons" || weightUnit == "TOns" || weightUnit == "TONs"|| weightUnit == "TONS")
        cout << " Mass = " << w * 142.857 << "stones";
    else
        cout << "Is an unknown unit and cannot be converted";

    return 0;
}// end of weightCov function


int main()
{
    for (;;)
    {
        // variable declaration
        string user;
        double mass;
        string unitType;

        //Prompt user to enter values
        cout << "Enter a mass and its unit type indicator(g,kg,lb,oz,long-tn,or sh-tn)" << endl;
        cin >> mass >> unitType;


        // Output Results
        cout << weightConv(mass, unitType) << endl;
        cout << "Would you like to do another calculation?(yes/no)";
        cin >> user;

        //Loop asking user if they want to do another calculation 
        if (user == "yes")
        {
            cout << "Enter a mass and its unit type indicator(g,kg,lb,oz,long tn,or sh tn)" << endl;
            cin >> mass >> unitType;
            cout << weightConv(mass, unitType) << endl;
        }
        else if (user == "no")
        {
            return 0;
        }
    }// end of for loop
}// end of main 

除一个错误外,程序运行良好。当结果打印出来时,它最后会增加一个零。我知道我在函数结束时返回0但是如果返回weightConv()它的无限递归。任何人都可以帮助我,以便它只返回答案而不是最后的零。提前谢谢。

1 个答案:

答案 0 :(得分:1)

您只是打印已转换的值,但您没有返回它。每个if块都应该包含一个返回计算结果的return语句。