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