Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

c++ - Recursive function does not return specified value

I am trying to debug a recursive function used to validate user input and return a value when the input is OK. The function looks like this:

double load_price()
{
    double price;

    Goods * tempGd = new Goods();

    cin >> price;

    while (!cin)
    {
        cin.clear();
#undef max
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '
');
        cout << endl;
        cout << "You didn't enter a number. Do so, please: ";
        cin >> price;
    } // endwhile
    if (!tempGd->set_price(price))
    {
        cout << endl;
        cout << "The price " << red << "must not" << white << " be negative." << endl;
        cout << "Please, insert a new price: ";
        load_price();
    }
    else
    {
        delete tempGd;
        return price;
    }
}

The method set_price() of Goods class looks as follows

bool Goods::set_price(double price)
{
    if (price> 0)
    {
        priceSingle_ = price;
        priceTotal_ = price* amount_;
        return true;
    }
    return false;
}

I tried drawing the problem on a paper but all my diagrams seem to look the way my function already looks like. I think there are some problems with returns, but I do not know where.

Help would be greatly appreciated.

question from:https://stackoverflow.com/questions/65909328/function-not-retaining-a-variable-value-during-recursion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're not using the return value of the recursive call. You need to do:

return load_price();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...