当用户输入负数C ++时断开循环

时间:2017-06-29 16:53:04

标签: c++ function loops

执行循环,让用户输入两个输入,这些输入将在函数中计算。该程序假设继续运行,直到为价格或标记输入负数。价格或负数加价的负数永远不会发送到calcRetail函数。

我的代码一直运行,直到我为标记输入一个负数。循环继续。我错过了什么,以便循环不仅在为价格输入负数时结束,而且在为标记输入负数时结束?

double calcRetail(double x = 0.0, double y = 0.0)
{
    double retail = x * (1 + (y / 100));
    return retail;
}
int main()
{
    double price = 0.0, markup = 0.0;
    while(price >= 0)
    {
        cout << "Enter the wholesale price of the item:" << endl;
        cin >> price;
        if(price >= 0)
        {
            cout << "Enter the percent markup of the item:" << endl;
            cin >> markup;

            cout << "$" << calcRetail(price,markup) << endl;
        }
    }

    return 0;
}

2 个答案:

答案 0 :(得分:1)

一些开发人员不赞成打破了。这样的事情就可以了:

bool isLooping = true;
while (isLooping)
{
    cout << "Enter the wholesale price of the item:" << endl;
    cin >> price;

    if ( price >= 0 )
    {
        cout << "Enter the percent markup of the item:" << endl;
        cin >> markup;

        if (markup >= 0) cout << "$" << calcRetail(price,markup) << endl;
        else isLooping = false;
    }
    else isLooping = false;
}

答案 1 :(得分:0)

这个怎么样?

while (true)
{
    cout << "Enter the wholesale price of the item:" << endl;
    cin >> price;

    if (price < 0) break;

    cout << "Enter the percent markup of the item:" << endl;
    cin >> markup;

    if (markup < 0) break;

    cout << "$" << calcRetail(price,markup) << endl;
}