C++ If语句逻辑

标签 c++ if-statement

我目前正在上 C++ 类(class),但出于某种原因,我在完成其中一项作业时遇到了一些小麻烦。

Asks a user the total amount of their purchase in a store and calculates their discount based on the following rule:

  • If they spend $50, give them a 10% discount
  • If they spend $75, the discount is 15%
  • If they spend $100, the discount is 25%
  • Finally, if they spend $250 or more, they get 40% off.
  • Display the amount of their purchase, subtract the discount and display the result.

这是我到目前为止编写的代码:

#include <iostream>
using namespace std;

int main() {

    double amount,discount=0.0;
    cout<<"Enter the total amount of your purchase: $";
    cin>>amount;
    cout<<endl;

    if (amount<50)
        cout<<"You do not recieve a discount"<<endl;
    else if(amount<=50.0)
    {
        discount=0.1*amount;
        cout<<"Discount: $"<<discount<<endl;
        amount=amount*0.9;
        cout<<"Total Amount: $"<<amount<<endl;
        return 0;
    }
    else if(amount<=75.0)
    {
        discount=0.15*amount;
        cout<<"Discount: $"<<discount<<endl;
        amount=amount*0.85;
        cout<<"Total Amount: $"<<amount<<endl;
        return 0;
    }
    else if(amount<=100.0)
    {
        discount=0.25*amount;
        cout<<"Discount: $"<<discount<<endl;
        amount=amount*0.75;
        cout<<"Total Amount: $"<<amount<<endl;
        return 0;
    }
    else if(amount<=250.0)
    {
        discount=0.4*amount;
        cout<<"Discount: $"<<discount<<endl;
        amount=amount*0.6;
        cout<<"Total Amount: $"<<amount<<endl;
        return 0;
    }
    return 0;
}

我没有收到正确的数字,例如,如果我输入 74,它会给我 11.1 我觉得这是我收到错误号码的一个简单原因,但我不确定为什么

最佳答案

让我们看看您的一个问题案例:

else if(amount<=50.0)

10% 的折扣适用于花费至少 50 美元的人 - 上面使用的测试将它限制为最多花费 50 美元的人(我们暂时忽略花费少于 50 美元的人已经被过滤掉了由前面的 if).

要创建一个 if 子句来决定一个人是否应该享受 10% 的折扣,您需要对数学表达式建模:

$50.00 <= amount < $75.00

该表达式自然地转换为以下 C 代码:

else if (50.00 <= amount && amount < 75.00)

如果您愿意,可以省略该表达式的第一部分 - 它由 else 子句之前的 if 处理:

if (amount < 50.00)
    cout<<"You do not receive a discount"<<endl;
else if (amount < 75.00)
    // etc...

关于C++ If语句逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25984878/

相关文章:

c++ - 使用 std::transform 打印 Map<string, vector<string*>> 时出错

c++ - 如果未使用方法本身,则忽略方法中的 undefined symbol

c++ - 如何创建大地形/景观

c++ - 在 Visual Studio 2010 中使用 C++ iostream

javascript - 有没有更好的方法在 JavaScript 中编写这个开关?

c++ - #define 和创建普通类型有什么区别?

if-statement - "IF"贵吗?

javascript - 让用户输入以 "BR"或 "BT"开头

c++ - 在 C++ 中截断文件

android - Java 中的多个 if 条件