实验四

任务二:

GradeCalc.hpp:

  1 #include<iostream>
  2 #include<vector>
  3 #include<string>
  4 #include<algorithm>
  5 #include<numeric>
  6 #include<iomanip>
  7 
  8 using std::vector;
  9 using std::string;
 10 using std::cin;
 11 using std::cout;
 12 using std::endl;
 13 
 14 class GradeCalc: public vector<int> {
 15     public:
 16         GradeCalc(const string &cname,int size);
 17         void input();
 18         void output() const;
 19         void sort(bool ascending = false);
 20         int min() const;
 21         int max() const;
 22         float average() const;
 23         void info();
 24 
 25     private:
 26         void compute();
 27 
 28     private:
 29         string course_name;
 30         int n;
 31         vector<int>    counts = vector<int>(5,0);
 32         vector<double> rates = vector<double>(5,0);
 33 };
 34 
 35 GradeCalc::GradeCalc(const string &cname,int size):course_name {cname},n {size} {};
 36 
 37 void GradeCalc::input() {
 38     int grade;
 39 
 40     for(int i = 0; i < n; ++i) {
 41         cin >> grade;
 42         this->push_back(grade);
 43     }
 44 }
 45 
 46 void GradeCalc::output() const {
 47     for(auto ptr = this->begin(); ptr != this->end(); ++ptr)
 48         cout << *ptr << " ";
 49     cout << endl;
 50 }
 51 
 52 void GradeCalc::sort(bool ascending) {
 53     if(ascending)
 54         std::sort(this->begin(),this->end());
 55     else
 56         std::sort(this->begin(),this->end(),std::greater<int>());
 57 }
 58 
 59 int GradeCalc::min() const {
 60     return *std::min_element(this->begin(),this->end());
 61 }
 62 
 63 int GradeCalc::max() const {
 64     return *std::max_element(this->begin(),this->end());
 65 }
 66 
 67 float GradeCalc::average() const {
 68     return std::accumulate(this->begin(),this->end(),0) * 1.0 / n;
 69 }
 70 
 71 void GradeCalc::compute() {
 72     for(int grade: *this) {
 73         if(grade < 60)
 74             counts.at(0)++;
 75         else if(grade >= 60 && grade < 70)
 76             counts.at(1)++;
 77         else if(grade >= 70 && grade < 80)
 78             counts.at(2)++;
 79         else if(grade >= 80 && grade < 90)
 80             counts.at(3)++;
 81         else if(grade >= 90)
 82             counts.at(4)++;
 83     }
 84 
 85     for(int i = 0; i < rates.size(); ++i)
 86         rates.at(i) = counts.at(i) * 1.0 / n;
 87 }
 88 
 89 void GradeCalc::info() {
 90     cout << "课程名称:\t" << course_name << endl;
 91     cout << "排序后成绩: \t";
 92     sort();
 93     output();
 94     cout << "最高分:\t" << max() << endl;
 95     cout << "最低分:\t" << min() << endl;
 96     cout << "平均分:\t" << std::fixed << std::setprecision(2) <<
 97          average() << endl;
 98     compute(); // 统计各分数段人数、比例
 99     vector<string> tmp {"[0, 60) ", "[60, 70)", "[70, 80)","[80, 90)",
100                         "[90, 100]"
101                        };
102     for(int i = tmp.size()-1; i >= 0; --i)
103         cout << tmp[i] << "\t: " << counts[i] << "人\t"
104              << std::fixed << std::setprecision(2) << rates[i]*100 <<
105              "%" << endl;
106 }

 

task2.cpp:

 1 #include "GradeCalc.hpp"
 2 #include<iomanip>
 3 
 4 void test(){
 5     int n;
 6     cout << "输入班级人数:";
 7     cin >> n;
 8     
 9     GradeCalc c1("OOP",n);
10     
11     cout << "录入成绩:" << endl;
12     c1.input();
13     cout << "输出成绩:" << endl;
14     c1.output();
15     
16     cout << string(20,'*') + "课程成绩信息" + string(20,'*') << endl;
17     c1.info();
18 }
19 
20 int main(){
21     test();
22 }

结果:

问题1:

成绩存在GradeCalc类的vector中;接口:this->begin()、this->end();input函数通过的接口:this->push_back;

问题2:

算平均数;有影响;“*1.0”可以把一个整数变为浮点数,去掉之后,无法得出小数的结果;

问题3:

没有检验输入数据是否有误(比如,成绩输入应在0-100);

 

任务三:

GradeCalc.hpp:

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <algorithm>
 5 #include <numeric>
 6 #include <iomanip>
 7 
 8 using std::vector;
 9 using std::string;
10 using std::cin;
11 using std::cout;
12 using std::endl;
13 
14 class GradeCalc {
15     public:
16         GradeCalc(const string &cname, int size);
17         void input(); // 录入成绩
18         void output() const; // 输出成绩
19         void sort(bool ascending = false); // 排序 (默认降序)
20         int min() const; // 返回最低分
21         int max() const; // 返回最高分
22         float average() const; // 返回平均分
23         void info(); // 输出课程成绩信息
24     private:
25         void compute(); // 成绩统计
26     private:
27         string course_name; // 课程名
28         int n; // 课程人数
29         vector<int> grades; // 课程成绩
30         vector<int> counts = vector<int>(5, 0); // 保存各分数段人数([0,60), [60, 70), [70, 80), [80, 90), [90, 100]
31         vector<double> rates = vector<double>(5, 0); // 保存各分数段比例
32 };
33 GradeCalc::GradeCalc(const string &cname, int size):
34     course_name {cname}, n {size} {}
35 void GradeCalc::input() {
36     int grade;
37     for(int i = 0; i < n; ++i) {
38         cin >> grade;
39         grades.push_back(grade);
40     }
41 }
42 void GradeCalc::output() const {
43     for(int grade: grades)
44         cout << grade << " ";
45     cout << endl;
46 }
47 void GradeCalc::sort(bool ascending) {
48     if(ascending)
49         std::sort(grades.begin(), grades.end());
50     else
51         std::sort(grades.begin(), grades.end(), std::greater<int>());
52 }
53 int GradeCalc::min() const {
54     return *std::min_element(grades.begin(), grades.end());
55 }
56 int GradeCalc::max() const {
57     return *std::max_element(grades.begin(), grades.end());
58 }
59 float GradeCalc::average() const {
60     return std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n;
61 }
62 void GradeCalc::compute() {
63     for(int grade: grades) {
64         if(grade < 60)
65             counts.at(0)++;
66         else if(grade >= 60 && grade < 70)
67             counts.at(1)++;
68         else if(grade >= 70 && grade < 80)
69             counts.at(2)++;
70         else if(grade >= 80 && grade < 90)
71             counts.at(3)++;
72         else if(grade >= 90)
73             counts.at(4)++;
74     }
75     for(int i = 0; i < rates.size(); ++i)
76         rates.at(i) = counts.at(i) *1.0 / n;
77 }
78 void GradeCalc::info() {
79     cout << "课程名称:\t" << course_name << endl;
80     cout << "排序后成绩: \t";
81     sort();
82     output();
83     cout << "最高分:\t" << max() << endl;
84     cout << "最低分:\t" << min() << endl;
85     cout << "平均分:\t" << std::fixed << std::setprecision(2) <<
86          average() << endl;
87     compute(); // 统计各分数段人数、比例
88     vector<string> tmp {"[0, 60) ", "[60, 70)", "[70, 80)","[80, 90)",
89                         "[90, 100]"
90                        };
91     for(int i = tmp.size()-1; i >= 0; --i)
92         cout << tmp[i] << "\t: " << counts[i] << "人\t"
93              << std::fixed << std::setprecision(2) << rates[i]*100 <<
94              "%" << endl;
95 }

 

task3.cpp:

 1 #include "GradeCalc.hpp"
 2 #include <iomanip>
 3 void test() {
 4     int n;
 5     cout << "输入班级人数: ";
 6     cin >> n;
 7     GradeCalc c1("OOP", n);
 8     cout << "录入成绩: " << endl;;
 9     c1.input();
10     cout << "输出成绩: " << endl;
11     c1.output();
12     cout << string(20, '*') + "课程成绩信息" + string(20, '*') << endl;
13     c1.info();
14 }
15 int main() {
16     test();
17 }

结果:

问题1:

成绩存在vector<int> grades中,通过变量名加“.”来访问;

问题二:

不一定必须要使用集成的方式来实现;

 

任务四:

task4-1.cpp:

 1 #include <iostream>
 2 #include <string>
 3 #include <limits>
 4 using namespace std;
 5 void test1() {
 6     string s1, s2;
 7     cin >> s1 >> s2; // cin: 从输入流读取字符串, 碰到空白符(空格/回车/Tab)即结束
 8     cout << "s1: " << s1 << endl;
 9     cout << "s2: " << s2 << endl;
10 }
11 void test2() {
12     string s1, s2;
13     getline(cin, s1); // getline(): 从输入流中提取字符串,直到遇到换行符
14     getline(cin, s2);
15     cout << "s1: " << s1 << endl;
16     cout << "s2: " << s2 << endl;
17 }
18 void test3() {
19     string s1, s2;
20     getline(cin, s1, ' '); //从输入流中提取字符串,直到遇到指定分隔符
21     getline(cin, s2);
22     cout << "s1: " << s1 << endl;
23     cout << "s2: " << s2 << endl;
24 }
25 int main() {
26     cout << "测试1: 使用标准输入流对象cin输入字符串" << endl;
27     test1();
28     cout << endl;
29     cin.ignore(numeric_limits<streamsize>::max(), '\n');
30     cout << "测试2: 使用函数getline()输入字符串" << endl;
31     test2();
32     cout << endl;
33     cout << "测试3: 使用函数getline()输入字符串, 指定字符串分隔符" << endl;
34     test3();
35 }

结果:

 

删除后结果:

 

问题:

避免影响下一次输入

task4-2.cpp:

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <limits>
 5 using namespace std;
 6 void output(const vector<string> &v) {
 7     for(auto &s: v)
 8         cout << s << endl;
 9 }
10 void test() {
11     int n;
12     while(cout << "Enter n: ", cin >> n) {
13         vector<string> v1;
14         for(int i = 0; i < n; ++i) {
15             string s;
16             cin >> s;
17             v1.push_back(s);
18         }
19         cout << "output v1: " << endl;
20         output(v1);
21         cout << endl;
22     }
23 }
24 int main() {
25     cout << "测试: 使用cin多组输入字符串" << endl;
26     test();
27 }
结果:

 

task4-3.cpp:

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 #include <limits>
 5 using namespace std;
 6 void output(const vector<string> &v) {
 7     for(auto &s: v)
 8         cout << s << endl;
 9 }
10 void test() {
11     int n;
12     while(cout << "Enter n: ", cin >> n) {
13         cin.ignore(numeric_limits<streamsize>::max(), '\n');
14         vector<string> v2;
15         for(int i = 0; i < n; ++i) {
16             string s;
17             getline(cin, s);
18             v2.push_back(s);
19         }
20         cout << "output v2: " << endl;
21         output(v2);
22         cout << endl;
23     }
24 }
25 int main() {
26     cout << "测试: 使用函数getline()多组输入字符串" << endl;
27     test();
28 }

结果:

删除后结果:

问题:

避免对下依次输入产生影响

任务五:

 grm.hpp

 1 #pragma once
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 template<typename T>
 7 class GameResourceManager {
 8     private:
 9         T resourse;
10         
11     public:
12         GameResourceManager(T res):resourse{res}{}
13         T get() const{
14             return resourse;
15         }
16         
17         void update(T sum){
18             resourse += sum;
19             if(resourse < 0)
20                 resourse = 0;
21         }
22 };

task5.cpp:

 1 #include "grm.hpp"
 2 #include <iostream>
 3 using std::cout;
 4 using std::endl;
 5 void test1() {
 6     GameResourceManager<float> HP_manager(99.99);
 7     cout << "当前生命值: " << HP_manager.get() << endl;
 8     HP_manager.update(9.99);
 9     cout << "增加9.99生命值后, 当前生命值: " << HP_manager.get() << endl;
10     HP_manager.update(-999.99);
11     cout <<"减少999.99生命值后, 当前生命值: " << HP_manager.get() << endl;
12 }
13 void test2() {
14     GameResourceManager<int> Gold_manager(100);
15     cout << "当前金币数量: " << Gold_manager.get() << endl;
16     Gold_manager.update(50);
17     cout << "增加50个金币后, 当前金币数量: " << Gold_manager.get() << endl;
18     Gold_manager.update(-99);
19     cout <<"减少99个金币后, 当前金币数量: " << Gold_manager.get() << endl;
20 }
21 int main() {
22     cout << "测试1: 用float类型对类模板GameResourceManager实例化" << endl;
23     test1();
24     cout << endl;
25     cout << "测试2: 用int类型对类模板GameResourceManager实例化" << endl;
26     test2();
27 }

结果:

 

任务六:

Info.hpp:

 1 #include<iostream>
 2 #include<iomanip>
 3 
 4 using namespace std;
 5 
 6 class Info {
 7     private:
 8         string nickname;
 9         string contact;
10         string city;
11         int n;
12     public:
13         Info(const string name,const string con, const string place, int num)
14         : nickname(name), contact(con), city(place), n(num) {}
15  
16     void display() const {
17         cout << "昵称: " << nickname << endl;
18         cout << "联系方式: " << contact << endl;
19         cout << "所在城市: " << city << endl;
20         cout << "预定参加人数: " << n << endl;
21     }
22 
23 
24 };

task6.cpp:

 1 #include"Info.hpp"
 2 
 3 #include<iostream>
 4 #include<vector>
 5 #include<string>
 6 
 7 using namespace std;
 8 
 9 int main() {
10     const int capacity = 100;
11     vector<Info> audience_lst;
12     string nickname,contact,city;
13     int n ,sum = 0,i = 0;
14     cout << "录入用户预约信息:" << endl;
15     cout << "昵称" << setw(40) << "联系方式(邮箱/手机号)" << setw(20) << "所在城市" << setw(20) << "预定参加人数" << endl;
16     while(cin >> nickname >> contact >> city >> n) {
17         int s = sum;
18         sum += n;
19         i++;
20         if(nickname == "0")
21             break;
22         else if(sum < 100) {
23             audience_lst.push_back(Info(nickname,contact,city,n));
24         } else if(sum > 100) {
25             sum = s;
26             i--;
27             cout << "对不起,只剩" <<100- s << "个名额" << endl;
28             cout << "1.输入u,更新(update)信息" << endl;
29             cout << "2.输入q,退出预定" << endl;
30             cout << "你的选择:" << endl;
31             string tem;
32             cin >> tem;
33             if(tem == "u") {
34                 cout << "请重新输入预定信息:" << endl;
35                 cin >> nickname >> contact >> city >> n;
36                 sum += n;
37                 i++;
38                 audience_lst.push_back(Info(nickname, contact, city, n));
39             } else break;
40         } else if(sum ==100) {
41             audience_lst.push_back(Info(nickname, contact, city, n));
42             break;
43         }
44     }
45     cout << "截至目前,一共有" << sum << "位听众预约,预约情况如下:" << endl;
46     int j;
47     for (j = 0; j < i; j++) {
48         audience_lst[j].display();
49     }
50     return 0;
51 }

结果:

 

任务七:

 date.h

 1 #pragma once
 2 #ifndef  DATE H
 3 #define  DATE H
 4 class Date {
 5 private:
 6     int year;
 7     int month;
 8     int day;
 9     int totalDays;
10 public:
11     Date(int year, int month, int day);
12     int getYear()const { return year; }
13     int getMonth()const { return month; }
14     int getDay()const { return day; }
15     int getMaxDay()const;
16     bool isLeapYear()const {
17         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
18     }
19     void show()const;
20     int distance(const Date& date)const {
21         return totalDays - date.totalDays;
22     }
23 };
24 #endif//  DATE H.

 

date.cpp:

 1 #include"date.h"
 2 #include<iostream>
 3 #include<cstdlib>
 4 using namespace std;
 5 namespace {
 6     const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 };
 7 }
 8 Date::Date(int year, int month, int day) :year{ year }, month{ month }, day{ day } {
 9     if (day <= 0 || day > getMaxDay()) {
10         cout << "Invalid date:";
11         show();
12         cout << endl;
13         exit(1);
14     }
15     int years = year - 1;
16     totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
17     if (isLeapYear() && month > 2)totalDays++;
18 }
19 int Date::getMaxDay()const {
20     if (isLeapYear() && month == 2)
21         return 29;
22     else return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
23 }
24 
25 void Date::show()const {
26     cout << getYear() << "-" << getMonth() << "-" << getDay();
27 }

 

accumulator.h:

 1 #pragma once
 2 #ifndef  ACCUMULATOR H
 3 #define  ACCUMULATOR H
 4 #include"date.h"
 5 class Accumulator {
 6 private:
 7     Date lastDate;
 8     double value;
 9     double sum;
10 public:
11     Accumulator(const Date& date, double value) :lastDate(date), value(value), sum{ 0 } {
12 }
13 
14     double getSum(const Date& date)const {
15         return sum + value * date.distance(lastDate);
16     }
17 
18     void change(const Date& date, double value) {
19         sum = getSum(date);
20         lastDate = date; this->value = value;
21     }
22 
23     void reset(const Date& date, double value) {
24         lastDate = date; this->value = value; sum = 0;
25     }
26 };
27 #endif//ACCUMULATOR H

 

account.h:

 1 #pragma once
 2 #ifndef  ACCOUNT H
 3 #define  ACCOUNT H
 4 #include"date.h"
 5 #include"accumulator.h"
 6 #include<string>
 7 class Account {
 8 private:
 9     std::string id;
10     double balance;
11     static double total;
12 protected:
13     Account(const Date& date, const std::string& id);
14     void record(const Date& date, double amount, const std::string& desc);
15     void error(const std::string& msg)const;
16 public:
17     const std::string& getId()const { return id; }
18     double getBalance()const { return balance; }
19     static double getTotal() { return total; }
20 
21     void show()const;
22 };
23 class SavingsAccount :public Account {
24 private:
25     Accumulator acc;
26     double rate;
27 public:
28     SavingsAccount(const Date& date, const std::string& id, double rate);
29     double getRate()const { return rate; }
30 
31     void deposit(const Date& date, double amount, const std::string& desc);
32     void withdraw(const Date& date, double amount, const std::string& desc);
33     void settle(const Date& date);
34 };
35 class CreditAccount :public Account {
36 private:
37     Accumulator acc;
38     double credit;
39     double rate;
40     double fee;
41     double getDebt()const {
42         double balance = getBalance();
43         return (balance < 0 ? balance : 0);
44     }
45 public:
46     CreditAccount(const Date& date, const std::string& id, double credit, double rate, double fee);
47     double getCredit()const { return credit; }
48     double getRate()const { return rate;}
49     double getAvailableCredit()const {
50         if (getBalance() < 0)
51             return credit + getBalance();
52         else
53             return credit;
54     }
55     void deposit(const Date& date, double amount, const std::string& desc);
56     void withdraw(const Date& date, double amount, const std::string& desc);
57     void settle(const Date& date);
58     void show()const;
59 };
60 #endif//ACCOUNT H

 

account.cpp

 1 #include"account.h"
 2 #include<cmath>
 3 #include<iostream>
 4 using namespace std;
 5 double Account::total = 0;
 6 
 7 Account::Account(const Date& date, const string& id) :id{ id }, balance{ 0 } {
 8     date.show(); cout << "\t#" << id << "created" << endl;
 9 }
10 
11 
12 void Account::record(const Date& date, double amount, const string& desc) {
13     amount = floor(amount * 100 + 0.5) / 100;
14     balance += amount;
15     total += amount;
16     date.show();
17     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
18 }
19 
20 void Account::show()const { cout << id << "\tBalance:" << balance; }
21 void Account::error(const string& msg)const {
22     cout << "Error(#" << id << "):" << msg << endl;
23 }
24 
25 SavingsAccount::SavingsAccount(const Date&date,const string&id,double rate):Account(date,id),rate(rate), acc(date,0){}
26 
27 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) {
28     record(date, amount, desc);
29     acc.change(date, getBalance());
30 }
31 
32 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) {
33     if (amount > getBalance()) {
34         error("not enough money");
35     }
36     else {
37         record(date, -amount, desc);
38         acc.change(date, getBalance());
39     }
40 }
41 
42 void SavingsAccount::settle(const Date& date) {
43     double interest = acc.getSum(date) * rate / date.distance(Date(date.getYear() - 1, 1, 1));
44     if (interest != 0)record(date, interest, "interest");
45     acc.reset(date, getBalance());
46 }
47 
48 CreditAccount::CreditAccount(const Date&date,const string&id,double credit,double rate,double fee):Account(date,id),credit(credit),rate(rate),fee(fee),acc(date,0){}
49 
50 void CreditAccount::deposit(const Date& date, double amount, const string& desc) {
51     record(date, amount, desc);
52     acc.change(date, getDebt());
53 }
54 
55 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) {
56     if (amount - getBalance() > credit) {
57         error("not enough credit");
58     }
59     else {
60         record(date, -amount, desc);
61         acc.change(date, getDebt());
62     }
63 }
64 
65 void CreditAccount::settle(const Date& date) {
66     double interest = acc.getSum(date) * rate;
67     if (interest != 0)record(date, interest, "interest");
68     if (date.getMonth() == 1)
69         record(date, -fee, "annual fee");
70     acc.reset(date, getDebt());
71 }
72 
73 void CreditAccount::show()const {
74     Account::show();
75     cout << "\tAvailable credit:" << getAvailableCredit();
76 }

 

task7.cpp:

 1 #include"account.h"
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 int main() {
 7     Date date(2008, 11, 1);
 8     SavingsAccount sa1(date, "S3755217", 0.015);
 9     SavingsAccount sa2(date, "02342342", 0.015);
10     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
11 
12     sa1.deposit(Date(2008, 11, 5), 5000, "salary");
13     ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell");
14     sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
15 
16     ca.settle(Date(2008, 12, 1));
17 
18     ca.deposit(Date(2008, 12, 1), 2016, "repay the credit");
19     sa1.deposit(Date(2008, 12, 5), 5500, "salary");
20 
21     sa1.settle(Date(2009, 1, 1));
22     sa2.settle(Date(2009, 1, 1));
23     ca.settle(Date(2009, 1, 1));
24 
25     cout << endl;
26     sa1.show(); cout << endl;
27     sa2.show(); cout << endl;
28     ca.show(); cout << endl;
29     cout << "Total:" << Account::getTotal() << endl;
30     return 0;
31 }

结果:

 

posted @ 2024-11-23 18:20  Bling888  阅读(13)  评论(0编辑  收藏  举报