【C++】课后练习题 p121 9

习题 9.9 商店销售某一商品,商店每天公布统一的折扣(discount)。同时允许销售人员在销售时灵活掌握售价(price),在此基础上,对一次购10件以上者,还可以享受9.8折优惠。

现已知当天3名销货员的销售情况为:
销货员号(num) 销货件数(quantity) 销货单价(price)
101 5 23.5
102 12 24.56
103 100 21.5

请编程序,计算出当日此商品的总销售款sum,以及每件商品的平均售价。要求用静态数据成员和静态成员函数。

/*
习题 9.9 商店销售某一商品,商店每天公布统一的折扣(discount)。同时允许销售人员在销售时灵活掌握售价(price),在此基础上,对一次购10件以上者,还可以享受9.8折优惠。

现已知当天3名销货员的销售情况为:
   销货员号(num)    销货件数(quantity)       销货单价(price)
   101                      5                                   23.5
   102                      12                                 24.56
   103                      100                               21.5

请编程序,计算出当日此商品的总销售款sum,以及每件商品的平均售价。要求用静态数据成员和静态成员函数。
*/
#include<iostream>
using namespace std;
class Product{
    public:
    // 构造函数
    Product(string n, int q, double p):num(n),quantity(q),price(p){}
    void total();
    static double average();
    static void display();

    private:
    string num;
    int quantity;
    double price;

    static double discount;
    static double sum;
    static int n;
};
// 初始化静态数据成员
double Product::discount = 0.98;
double Product::sum = 0.0;
int Product::n = 0;

int main(){
    int i;
	Product p[3] =
	{
		Product("101",5,23.5),
		Product("102",12,24.56),
		Product("103",100,21.5)
	};
 
	for (i = 0; i != 3; ++i)
	{
		p[i].total();
	}
 
	Product::display();
 
	return 0;
}

double Product::average(){
    return sum/n;
}

void Product::display()
{
	cout << "平均售价为:"<< average()  << endl;
	cout << "总销售款为:" << sum << endl;

}
void Product::total(){
    n += quantity;
    if (quantity > 10){
        sum += quantity * price * discount;
    }else{
        sum += quantity * price;
    }
}

这道题很有意思,每个货号的商品是一个对象。
而商品的总销售额是静态的,平均也是静态的,这就要求,总件数n 也是静态的,搞清楚这三者的关系后,这道题其实不太难!

猜你喜欢

转载自blog.csdn.net/weixin_40293999/article/details/132542480