OJ 2064 Problem D 水果店

Description

小明经营着一个不大的水果店(似曾相识哦~),只销售苹果、香蕉和桔子。为了促销,小明制定了如下定价策略:

  1. 苹果:按斤论价,每斤P元,买W斤,则需支付W * P元。

  2. 香蕉:半价,每斤P元,买W斤,则需支付W / 2 * P元。

3.桔子:按斤论价,每斤P元,买W斤。如果W>10,则打半价,即需支付W * P / 2元;否则如果W>5,则打八折,即需支付W * P * 0.8元;其他情况不打折,即需支付W * P元。

请用C++来计算某个顾客采购的水果的总价。该程序至少应有:

  1. Fruit类:是个抽象类,是Apple、Banana和Orange的父类。支持重载的加法运算。

  2. Apple、Banana和Orange类:分别对应于苹果、香蕉和桔子三种水果,每种水果执行不同的定价策略。

Input

输入为多行,每行格式为:

C W P

其中C是水果类型(a、b、o分别代表苹果、香蕉和桔子),W和P分别是顾客购买的相应水果的重量和每斤水果的单价。

Output

输出顾客需支付的总金额。

Sample Input

a 1 1
b 1 1
o 1 1

Sample Output

2.5

HINT

注意包含vector容器的头文件。

需要用多态来实现。

Append Code

int main()
{
    vector<Fruit*> fruits;
    vector<Fruit*>::iterator itr;
    char type;
    double weight, price, totalPrice;
    while (cin>>type>>weight>>price)
    {
        switch(type)
        {
        case 'a':
            fruits.push_back(new Apple(weight, price));
            break;
        case 'b':
            fruits.push_back(new Banana(weight,price));
            break;
        case 'o':
            fruits.push_back(new Orange(weight, price));
            break;
        }
    }
    totalPrice = 0;
    for (itr = fruits.begin(); itr != fruits.end(); itr++)
    {
        totalPrice = **itr + totalPrice;
    }
    cout<<totalPrice<<endl;
    return 0;
}

Accepted Code

/**
 *  OJ 作业九
 *  2020年6月5日07:55:51
 */
#include <iostream>
#include <string>
#include <iomanip>
#include <typeinfo>
#include <vector>
using namespace std;

class Fruit {
protected:
    double price;
    double weight;
public:
    Fruit(double W = 0, double P = 0) : price(P), weight(W) {}
    virtual double getPrice() = 0;
    friend double operator +(Fruit &f, double totalPrice) {
        return f.getPrice() + totalPrice;
    }
};
class Apple : public Fruit {
public:
    Apple(double w, double p) : Fruit(w, p) {}
    double getPrice() {
        return weight * price;
    }
};
class Banana : public Fruit {
public:
    Banana(double w, double p) : Fruit(w, p) {}
    double getPrice() {
        return weight * 0.5 * price;
    }
};
class Orange : public Fruit {
public:
    Orange(double w, double p) : Fruit(w, p) {}
    double getPrice() {
        if (weight > 10) return weight*price * 0.5;
        else if (weight > 5) return weight*price*0.8;
        else return weight*price;
    }
};
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值