原题见谭浩强C++课本第九章(P295)第九题
题目:商店销售某一商品,每天公布统一的折扣。同时允许销售人员在销售是灵活掌握售价,在此基础上,一次购时间以上者,享受98折优惠,现已知当天3个销售员销售情况为:
销售员号(num) | 销货件数(quantity) | 销货单价(price) |
101 | 5 | 23.5 |
102 | 12 | 24.56 |
103 | 100 | 21.5 |
请编写程序,计算当日此产品的总销售款sum以及每件商品的平均单价,要求用静态成员和静态成员函数。
#include<iostream>
using namespace std;
class Sale {
private:int num;//工号int quantity;//每个人销售的件数double price;//销售单价static double sum;//总销售款static double discount;static int n;//总销售件数
public:Sale(int n, int q, double p) {num = n;quantity = q;price = p;}static double average();friend void inputdiscount();static void print(Sale s[]);void cal() {if (quantity <= 10) {sum += quantity * discount * price;}else {sum += quantity * discount * price * 0.98;}n += quantity;}};
double Sale::sum = 0;
int Sale::n = 0;
double Sale::discount = 1;
void inputdiscount() {cin >> Sale::discount;
}double Sale::average() {return sum / n;
}
void Sale::print(Sale s[]) {for (int i = 0; i < 3; i++) {cout << "number: " << s[i].num << " quantity: " << s[i].quantity << " price: " << s[i].price << endl;}cout << "sum: " << sum << " sum of quantity: " << n << " average: " << average() << endl;
}
int main() {Sale s[3]{Sale(101,5,23.5),Sale(102,12,23.56),Sale(103,100,21.5),};inputdiscount();for (int i = 0; i < 3; i++)s[i].cal();s[0].print(s);
}
输出结果: