C++面向对象程序设计——简单的商品销售题
问题描述:
店销售某一商品,商店每天公布统一的折扣(discount)。同时允许销售人员在销售时灵活掌握售价(price),在此基础上,对一次购10件以上者,还可以享受98折优待。现已知当天3个销货员销售情况为
销售员号(num) 销货件数(quantity) 销货单价(price)
101 5 23.5
102 12 24.56
103 100 21.5
请编程序,计算出当日此商品的总销售款sum以及每件商品的平均售价。要求用静态据成员和静态成员函数。
提示:将折扣discount,总销售款sum和商品销售总件数n,声明为静态数据成员,定义静态成员函数average(求平均售价)和display(输出结果)。
#include<iostream>
using namespace std;
//商店销售某一商品,每天公布同一的折扣(discount),销售人员灵活掌握售价(price),此外,一次购买10件以上者,享受0.98折扣
//目的:计算出当日此商品的总销售款sum和每件商品的平均售价。
class Product //声明商品的类
{
public: //公用继承
Product(int n,int q,float p):num(n),quantity(q),price(p){} //商品的构造函数,总销售款,销货件数,销货单价
void total(); //总销售
static float average(); //计算平均售价
static void display(); //打印输出
private:
int num; //销货员号
int quantity; //销货件数
float price; //销货单价
static float discount; //折扣
static float sum; //总销售款
static int n; //商品销售总件数
};
void Product::total() //计算总销售款
{
float rate = 1.0; //打折初始值为1
if (quantity>10) rate = rate*0.98; //如果购买数量大于10件,打98折扣
sum = sum+quantity*price*rate*(1-discount); //单个销售员号的销售款
n=n+quantity; //单个销货件数
}
void Product::display()
{
cout<<"总销售额:"<<sum<<endl;
cout<<"每件商品的平均售价:"<<average()<<endl;
}
float Product::average()
{
return (sum/n);
}
float Product::discount=0.05 ; //公布的统一折扣
float Product::sum = 0; //
int Product::n = 0;
int main()
{
Product Prod[3] = {Product(101,2,23.5),Product(102,12,24.56),Product(103,100,21.5)}; //用类定义一个对象数组,将销售员的数据存入数组
for (int i =0;i<3;i++) //计算总销售款SUM
{
Prod[i].total();
}
Product::display(); //打印输出
return 0;
}