为什么在调用函数时答案会以无限循环的形式返回?

时间:2015-01-27 07:38:26

标签: c++

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

using namespace std;

double weightConv(double w , string weightUnit)
{
    if (weightUnit == "g" || "G")
        cout << w * 0.035274 << "oz";
    else if (weightUnit == "oz" || "OZ" || "oZ" || "Oz")
        cout << w / 28.3495 << "g";
    else if (weightUnit == "kg" || "KG" || "Kg" || "kG")
        cout << w * 2.20462 << "lb";
    else if (weightUnit == "lb" || "LB" || "Lb" || "lB")
        cout << w / 0.453592 << "kg";
    else if (weightUnit == "ton" || "tn" || "TON" || "TN")
        cout << w * 1.10231 << "sh tn";
    else if (weightUnit == "sh tn" || "SH TN")
        cout <<  w / 0.90718 << "tn";
    else
        cout << "Invalid unit of measurement";

    return weightConv(w, weightUnit);
}// end of weightCov function


int main()
{
    string user;
    double mass;
    string unitType;

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


    // case sensitive characters
    //regex reg_icase("g", regex::icase);
    //if (regex_match("G", reg_icase))

    double answer = weightConv(mass, unitType);

// Output Results
    cout << " Mass = " << answer << endl;

    if (user == "exit")
    {
        return 0;
    }

}// end of main

由于某些奇怪的原因,当我通过cin输入数字和字符串并尝试通过调用函数weightConv来打印答案时,它会给出一个无限循环。有人可以帮我修改我的代码吗?

2 个答案:

答案 0 :(得分:4)

这是无限递归:weightConv()自称。

答案 1 :(得分:0)

这是一种无休止的递归,因为weightConv()一次又一次地调用自身Segmentation Fault。此外,您永远不会输入字符串user,因此,应在weightConv()函数之后将其删除或输入。