我目前正在使用C ++上一堂课,由于某种原因,我遇到一些麻烦。


  询问用户在商店中的购买总额,以及
  根据以下规则计算折扣:
  
  
  如果他们花费$ 50,请给他们10%的折扣
  如果他们花费$ 75,折扣为15%
  如果他们花费$ 100,折扣为25%
  最后,如果他们花费250美元或更多,他们将获得40%的折扣。
  显示他们的购买金额,减去折扣并显示结果。
  


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

#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
我觉得这是我输入错误号码的简单原因,但我不确定为什么

最佳答案

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>=250.0)//250 or more
{
    discount=0.4*amount;
    cout<<"Discount: $"<<discount<<endl;
    amount=amount*0.6;
    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>=75.0)
{
    discount=0.15*amount;
    cout<<"Discount: $"<<discount<<endl;
    amount=amount*0.85;
    cout<<"Total Amount: $"<<amount<<endl;
    return 0;
}
else if(amount>=50.0)
{
    discount=0.1*amount;
    cout<<"Discount: $"<<discount<<endl;
    amount=amount*0.9;
    cout<<"Total Amount: $"<<amount<<endl;
    return 0;
}

return 0;
}

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

10-11 21:03