c++ - 在if语句中需要帮助

标签 c++

首先,让我向您展示代码:

// 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这样的表达式实际上是使用逗号运算符的,该运算符将同时评估valAvalB,但得出单个值valB
在您的特定情况下,由于逗号运算符的优先级相对较低,因此更为复杂,因此unitsPurchased >= 10, 19表示(unitsPurchased >= 10), 19,它等于:
  • 评估unitsPurchased >= 10;
  • 评估19;
  • 使用值19

  • 由于19不为零,因此将其视为true。因此,由于每次购买都会产生20%的折扣,您的企业更有可能破产:-)

    关于c++ - 在if语句中需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62629262/

    相关文章:

    c++ - 如何检查是否可以在Windows上创建路径?

    c++ - 将数据写入文件的 'best' 方法是什么,稍后再次读入。

    c++ - 派生类型名

    c++ - 内联函数

    c++ - 如何在Sentry on-premise 版本中创建CPP 项目

    c++ - 对象按值传递与按引用传递时运行速度慢

    c++ - 指向成员表达式 UB 的指针

    c++将结构 append 到二进制文件中

    c++ - 是否有一些类似于 boost program_options 但用于 *keyboard shortcut auto-gen help* 的 c++ 库/源代码?

    c++ - 了解 std::string_view 的不同构造