首先,让我向您展示代码:
// calculate grand total
if(unitsPurchased >= 10,19)
{
discount = .20;
totalCost = totalCost - (totalCost * discount);
cout << fixed << setprecision(2);
cout << "\tBecuase you purchased " << unitsPurchased << " Units,\n\tYou get a 20% discount!" << "The grand total is: $" << totalCost << endl;
}
如果有人在20%
之间购买商品,我将尝试使用10 to 19 items
折扣。如何更改我的if语句以反射(reflect)这一点?我尝试使用AND (&&)
,但是没有用。如何设置两个数字之间的范围?
最佳答案
您要查找的语句是以下之一:
if (unitsPurchased > 10 && unitsPurchased < 19) { // exclude 10, 19
if (unitsPurchased >= 10 && unitsPurchased < 19) { // include 10, exclude 19
if (unitsPurchased >= 10 && unitsPurchased <= 19) { // include 10, 19
像valA, valB
这样的表达式实际上是使用逗号运算符的,该运算符将同时评估valA
和valB
,但得出单个值valB
。在您的特定情况下,由于逗号运算符的优先级相对较低,因此更为复杂,因此
unitsPurchased >= 10, 19
表示(unitsPurchased >= 10), 19
,它等于:unitsPurchased >= 10
; 19
; 19
。 由于
19
不为零,因此将其视为true。因此,由于每次购买都会产生20%的折扣,您的企业更有可能破产:-)
关于c++ - 在if语句中需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62629262/