题目描述
小明经营着一个不大的水果店(似曾相识哦~),只销售苹果、香蕉和桔子。为了促销,小明制定了如下定价策略:
- 苹果:按斤论价,每斤P元,买W斤,则需支付W*P元。
- 香蕉:半价,每斤P元,买W斤,则需支付W/2*P元。
- 桔子:按斤论价,每斤P元,买W斤。如果W>10,则打半价,即需支付W * P/2元;否则如果W>5,则打八折,即需支付W * P * 0.8元;其他情况不打折,即需支付W*P元。
请用C++来计算某个顾客采购的水果的总价。该程序至少应有: - Fruit类:是个抽象类,是Apple、Banana和Orange的父类。支持重载的加法运算。
- Apple、Banana和Orange类:分别对应于苹果、香蕉和桔子三种水果,每种水果执行不同的定价策略。
输入
输入为多行,每行格式为:
C W P
其中C是水果类型(a、b、o分别代表苹果、香蕉和桔子),W和P分别是顾客购买的相应水果的重量和每斤水果的单价。输入完成后输入字符q结束输入。
输出
输出顾客需支付的总金额。
样例输入
a 1 1
b 1 1
o 1 1
q
样例输出
2.5
#include<iostream>
using namespace std;
class Fruit {
public:
virtual double sum()=0;
friend double operator +(Fruit &x,double ans);
};
class Apple:public Fruit {
private:
double p,w;
public:
Apple(double x,double y) {
w=x,p=y;
}
virtual double sum() {
return p*w;
}
};
class Banana:public Fruit {
private:
double p,w;
public:
Banana(double x,double y) {
w=x,p=y;
}
virtual double sum() {
return p*w/2;
}
};
class Orange:public Fruit {
private:
double p,w;
public:
Orange(double x,double y) {
w=x,p=y;
}
virtual double sum() {
if(w>10) return p*w/2;
if(w>5) return p*w*0.8;
return p*w;
}
};
double operator +(Fruit &x,double ans) {
ans+=x.sum();
return ans;
}
int main() {
Fruit* fru[105];
char a;
int tot=1;
cin>>a;
double w,p,ans=0;
while(a!='q') {
getchar();
cin>>w>>p;
if(a=='a') {
fru[tot]=new Apple(w,p);
tot++;
}
if(a=='b') {
fru[tot]=new Banana(w,p);
tot++;
}
if(a=='o') {
fru[tot]=new Orange(w,p);
tot++;
}
getchar();
cin>>a;
}
for(int i=1;i<tot;i++) {
ans=*fru[i]+ans;
}
cout<<ans;
return 0;
}