C++ 当用户输入负数C++;

C++ 当用户输入负数C++;,c++,function,loops,C++,Function,Loops,执行一个循环,让用户输入两个将在函数中计算的输入。假定程序继续运行,直到为价格或加价输入负数为止。价格或负加价的负数永远不会发送到calcRetail函数 我的代码一直运行,直到为标记输入负数为止。循环继续。我遗漏了什么,这样循环不仅在为价格输入负数时结束,而且在为标记输入负数时结束 double calcRetail(double x = 0.0, double y = 0.0) { double retail = x * (1 + (y / 100)); return ret

执行一个循环,让用户输入两个将在函数中计算的输入。假定程序继续运行,直到为价格或加价输入负数为止。价格或负加价的负数永远不会发送到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;
}
double calcRetail(双x=0.0,双y=0.0)
{
双零售=x*(1+(y/100));
退货零售;
}
int main()
{
双倍价格=0.0,加价=0.0;
而(价格>=0)
{
价格;
如果(价格>=0)
{
cout标记;
这个怎么样

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;
}
while(true)
{
价格;
如果(价格<0)中断;
cout标记;
如果(标记<0)中断;

cout一些开发人员不赞成中断。类似这样的方式也可以:

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;
}
bool isLooping=true;
while(isLooping)
{
价格;
如果(价格>=0)
{
cout标记;

如果(标记>=0)不能
if(价格<0)在
cin
之后立即中断;
之外返回0
,而
循环移动
在循环之外返回0;
。解决此类问题的正确工具是调试器。在询问堆栈溢出之前,您应该逐行检查代码。有关更多帮助,请阅读。至少,您应该我们的问题包括一个重现您的问题的示例,以及您在调试器中的观察结果。@πάνταῥεῖ 循环中的
返回0;
只是错误的代码格式。在一行末尾有一个右大括号。(这可能是我试图修复缩进时的错误。)@πάνταῥεῖ 什么?我是说
返回0;
不在循环中。它只是因为不正确的缩进而看起来是这样。这是负价格的中断。他希望负价格和加价的中断。是的,但它显示了OP需要使用的技术。我唯一要添加的是一个警告和一个指向@buttonsrtoys的链接。这在负价格或负价格时中断自动加价。我相信这就是要求?即使输入了负价格,您的代码也会要求加价。您还放弃了计算,这将不得不进入
else
(另外,您希望
|
,而不是
&
,在您的条件下结束循环。)