【问题标题】:break a loop when user enters negative number C++当用户输入负数 C++ 时中断循环
【发布时间】:2017-06-29 16:53:03
【问题描述】:

执行一个循环,让用户输入两个将在函数中计算的输入。假设程序将继续运行,直到为价格或加价输入负数。价格或负标记的负数永远不会发送到 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;
}

【问题讨论】:

  • if (price &lt; 0) break;cinreturn 0 之后while 循环之外
  • return 0;移出循环。
  • 调试器是解决此类问题的正确工具。 询问 Stack Overflow 之前,您应该逐行逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该在edit 您的问题中包含一个重现您的问题的Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
  • @πάνταῥεῖ 循环内的return 0; 只是错误的代码格式。一行的末尾有一个右花括号。 (当我试图修复缩进时,这可能是我的错。)
  • @πάνταῥεῖ 什么?我是说return 0; not 在循环内。由于缩进不正确,它看起来就是这样。

标签: c++ function loops


【解决方案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;
}

【讨论】:

  • 即使在输入负价格后,您的代码也会要求加价。您还放弃了计算,它必须进入else。 (另外,您希望 ||,而不是 &amp;&amp; 在您的条件下结束循环。)
【解决方案2】:

这个怎么样?

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;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2016-12-28
  • 2013-03-13
  • 1970-01-01
  • 2023-03-16
  • 2018-07-25
  • 2014-01-01
相关资源
最近更新 更多