实验4 类的组合、继承、模板类、标准库

task2:

代码:

  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);      // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
 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();  output();
 93     cout << "最高分:\t" << max() << endl;
 94     cout << "最低分:\t" << min() << endl;
 95     cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl;
 96     
 97     compute();  // 统计各分数段人数、比例
 98 
 99     vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"};
100     for(int i = tmp.size()-1; i >= 0; --i)
101         cout << tmp[i] << "\t: " << counts[i] << "人\t" 
102              << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 
103 } 
View Code
 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 }
View Code

截图:

 

问题1:

成绩存储在:通过this指针存在push_back(grade)中;通过this指针进行访问

问题2:

作用:对于班级总成绩进行求平均,同时明确输出的平均值为float型数据,没有影响,作用是将整型的总成绩变为浮点型数据

问题3:

对于各分数段成绩的统计,对于总分不同的成绩统计不太适用

task3:

代码:

  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 
 25 private:
 26     void compute();     // 成绩统计
 27 
 28 private:
 29     string course_name;     // 课程名
 30     int n;                  // 课程人数
 31     vector<int> grades;     // 课程成绩
 32     vector<int> counts = vector<int>(5, 0);      // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100]
 33     vector<double> rates = vector<double>(5, 0); // 保存各分数段比例 
 34 };
 35 
 36 GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {}   
 37 
 38 void GradeCalc::input() {
 39     int grade;
 40 
 41     for(int i = 0; i < n; ++i) {
 42         cin >> grade;
 43         grades.push_back(grade);
 44     } 
 45 }  
 46 
 47 void GradeCalc::output() const {
 48     for(int grade: grades)
 49         cout << grade << " ";
 50     cout << endl;
 51 } 
 52 
 53 void GradeCalc::sort(bool ascending) {
 54     if(ascending)
 55         std::sort(grades.begin(), grades.end());
 56     else
 57         std::sort(grades.begin(), grades.end(), std::greater<int>());
 58         
 59 }  
 60 
 61 int GradeCalc::min() const {
 62     return *std::min_element(grades.begin(), grades.end());
 63 }  
 64 
 65 int GradeCalc::max() const {
 66     return *std::max_element(grades.begin(), grades.end());
 67 }    
 68 
 69 float GradeCalc::average() const {
 70     return std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n;
 71 }   
 72 
 73 void GradeCalc::compute() {
 74     for(int grade: grades) {
 75         if(grade < 60)
 76             counts.at(0)++;
 77         else if(grade >= 60 && grade < 70)
 78             counts.at(1)++;
 79         else if(grade >= 70 && grade < 80)
 80             counts.at(2)++;
 81         else if(grade >= 80 && grade < 90)
 82             counts.at(3)++;
 83         else if(grade >= 90)
 84             counts.at(4)++;
 85     }
 86 
 87     for(int i = 0; i < rates.size(); ++i)
 88         rates.at(i) = counts.at(i) *1.0 / n;
 89 }
 90 
 91 void GradeCalc::info()  {
 92     cout << "课程名称:\t" << course_name << endl;
 93     cout << "排序后成绩: \t";
 94     sort();  output();
 95     cout << "最高分:\t" << max() << endl;
 96     cout << "最低分:\t" << min() << endl;
 97     cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl;
 98     
 99     compute();  // 统计各分数段人数、比例
100 
101     vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"};
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 << "%" << endl; 
105 } 
View Code
 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 }
View Code

截图:

 

问题1:

直接存储到了<vector>grades 当中;

是通过grades直接访问,减少了对this->指针的使用

问题2:

实验三对于成绩的存储,直接选用增加一个<vector>grades直接存入成绩,更加方便,直接

task4.1:

代码:

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

截图:

 

问题1:作用:防止test1最后输入的换行操作对test2产生影响。

task4.2:

代码:

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

截图:

 

task4.3:

代码:

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

截图:

 

问题:

 

用途:消除上一次测试对本次测试的影响。

task 5:

代码:

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

task6:

代码:

 1 hpp
 2 #pragma once
 3 #include<iostream>
 4 #include<iomanip>
 5 using namespace std;
 6 class Info {
 7 public:
 8     string nickname;
 9     string contact;
10     string city;
11     int n;
12 public:
13     Info(string nickname_,string contact_,string city_,int n_):nickname(nickname_),contact(contact_),city(city_), n(n_) {}
14     void display()const {
15         cout << string(40, '*') << endl;
16         cout <<  "昵称:" << "\t" << nickname << endl;
17         cout << "联系方式:" << "\t" << contact << endl;
18         cout <<  "所在城市:" << "\t" << city << endl;
19         cout << "预定人数:" << "\t" << n << endl;
20    }
21 };
View Code
 1 cpp
 2 #include"Info.hpp"
 3 #include<iomanip>
 4 #include<vector>
 5 const int capacity = 100;
 6 int main() {
 7     cout << "录入用户预约信息:" << endl;
 8     cout << "录入用户数:";
 9     int n;
10     cin >> n;
11     cout << "昵称" << "\t" << "联系方式(邮箱/手机号)" << "\t" << "所在城市" << "\t" << "预定参加人数" << endl;
12     vector<Info> v;
13     string nickname;
14     string contact;
15     string city;
16     int num;
17     int sum = 0;
18     for (int i = 0; i < n; i++) {
19         cin >> nickname >> contact >> city >> num;
20         sum += num;
21         if (sum > capacity) {
22             char choice;
23             cout << "对不起,只剩" << 100 + num - sum << "个位置" << endl;
24             cout << "1. 输入u,更新(update)预定信息" << endl;
25             cout << "2. 输入q,退出预定" << endl;
26             cout << "你的选择: ";
27             cin >> choice;
28             if (choice == 'u') {
29                 sum -= num;
30                 cout << "请重新输入预定信息" << endl;
31                 cin >> nickname >> contact >> city >> num;
32                  sum += num;
33             }
34              else if(choice=='q') {
35                 continue;
36             }
37         }
38         v.push_back(Info(nickname, contact, city, num));
39     }
40     cout << "截至目前,一共有" << sum << "位听众预约。" << "预约听众信息如下:" << endl;
41     for (auto i : v) {
42          i.display();
43      }
44     cout << string(40, '*');
45     return 0;
46 }
View Code

 

截图:

task7:

代码:

1 date.h
  2 #pragma once
  3 class Date {
  4 private:
  5     int year;
  6     int month;
  7     int day;
  8     int totalDays;
  9 public:
 10     Date(int year, int month, int day);
 11     int getYear()const { return year; }
 12     int getMonth()const { return month; }
 13     int getDay()const { return day; }
 14     int getMaxDay()const;
 15     bool isLeapYear()const {
 16         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
 17     }
 18     void show() const;
 19     int distance(const Date& date)const {
 20         return totalDays - date.totalDays;
 21     }
 22 };
 23 accumulator.h
 24 #pragma once
 25 #include "date.h"
 26 class Accumulator {
 27 private:
 28     Date lastDate;
 29     double value;
 30     double sum;
 31 public:
 32     Accumulator(const Date&date,double value):lastDate(date),value(value),sum{0}{}
 33     double getSum(const Date& date) const {
 34         return sum + value * date.distance(lastDate);
 35     }
 36     void change(const Date& date, double value) {
 37         sum = getSum(date);
 38         lastDate = date;
 39         this->value = value;
 40     }
 41     void reset(const Date& date, double value) {
 42         lastDate = date;
 43         this->value;
 44         sum = 0;
 45     }
 46 };
 47 account.h
 48 #pragma once
 49 #include"date.h"
 50 #include"accumulator.h"
 51 #include<string>
 52 using namespace std;
 53 class Account {
 54 private:
 55     string id;
 56     double balance;
 57     static double total;
 58 protected:
 59     Account(const Date& date, const string &id);
 60     void record(const Date& date, double amount, const string& desc);
 61     void error(const string& msg) const;
 62 public:const string& getId() { return id; }
 63       double getBalance()const { return balance; }
 64       static double getTotal() { return total; }
 65       void show()const;
 66 };
 67 class SavingsAccount:public Account {
 68 private:
 69     Accumulator acc;
 70     double rate;
 71 public:
 72     SavingsAccount(const Date& date, const string& id, double rate);
 73     double getRate() const { return  rate; }
 74     void deposit(const Date& date, double amount, const string& desc);
 75     void withdraw(const Date& date, double amount, const string& desc);
 76     void settle(const Date& date);
 77 };
 78 class CreditAccount :public Account {
 79 private:
 80     Accumulator acc;
 81     double credit;
 82     double rate;
 83     double fee;
 84     double getDebt()const {
 85         double balance = getBalance();
 86         return(balance < 0 ? balance : 0);
 87     }
 88 public:CreditAccount(const Date& date, const string& id, double credit, double rate, double fee);
 89       double getCredit()const { return credit; }
 90       double getRate()const { return rate; }
 91       double getFee() const { return fee; }
 92       double getAvailableCredit()const {
 93           if (getBalance() < 0)return credit + getBalance();
 94           else return credit;
 95       }
 96       void deposit(const Date& date, double amount, const string& desc);
 97       void withdraw(const Date& date, double amount, const string& desc);
 98       void settle(const Date& date);
 99       void show()const;
100 };
101 
102 date.cpp
103 #include"date.h"
104 #include<iostream>
105 #include<cstdlib>
106 using namespace std;
107 namespace {
108     const int DAYS_BEFIRE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304 ,334,365 };
109 }
110 Date::Date(int year, int month, int day) :year(year), month(month), day(day) {
111     if (day <= 0 || day > getMaxDay()) {
112         cout << "Invalid date: ";
113         show();
114         cout << endl;
115         exit(1);
116     }
117     int years = year - 1;
118     totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFIRE_MONTH[month - 1] + day;
119     if (isLeapYear() && month > 2) totalDays++;
120 }
121 int Date::getMaxDay()const {
122     if (isLeapYear() && month == 2)
123         return 29;
124     else return DAYS_BEFIRE_MONTH[month] - DAYS_BEFIRE_MONTH[month - 1];
125 }
126 void Date::show()const {
127     cout << getYear() << "-" << getMonth() << "-" << getDay();
128 }
129 
130 accumulator.cpp
131 #include "account.h"
132 #include <cmath>
133 #include<iostream>
134 using namespace std;
135 double Account::total = 0;
136 Account::Account(const Date& date, const string& id) :id(id), balance(0) {
137     date.show();
138     cout << "\t#" << id << "created" << endl;
139 }
140 void Account::record(const Date& date, double amount, const string& desc) {
141     amount = floor(amount * 100 + 0.5) / 100;
142     balance += amount;
143     total += amount;
144     date.show();
145     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
146 }
147 void Account::show()const { cout << id << "\tBalance:" << balance; }
148 void Account::error(const string& msg)const {
149     cout << "Error(#" << id << "):" << msg << endl;
150 }
151 SavingsAccount::SavingsAccount(const Date&date,const string &id,double rate):Account(date,id),rate(rate),acc(date,0){}
152 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) {
153     record(date, amount, desc);
154     acc.change(date, getBalance());
155 }
156 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) {
157     if (amount > getBalance()) {
158         error("not enough money");
159     }
160     else {
161         record(date, -amount, desc);
162         acc.change(date, getBalance());
163     }
164 }
165 void SavingsAccount::settle(const Date& date) {
166     double interest = acc.getSum(date) * rate/date.distance(Date(date.getYear()-1,1,1));
167     if (interest != 0)record(date, interest, "interest");
168     acc.reset(date, getBalance());
169 }
170 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){}
171 void CreditAccount::deposit(const Date& date, double amount, const string& desc) {
172     record(date, amount, desc);
173     acc.change(date, getDebt());
174 }
175 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) {
176     if (amount - getBalance() > credit) {
177         error("not enouogh credit");
178     }
179     else {
180         record(date, -amount, desc);
181         acc.change(date, getDebt());
182     }
183 }
184 void CreditAccount::settle(const Date& date) {
185     double interest = acc.getSum(date) * rate;
186     if (interest != 0) record(date, interest, "interest");
187     if (date.getMonth() == 1)record(date, -fee, "annual fee");
188     acc.reset(date, getDebt());
189 }
190 void CreditAccount::show()const {
191     Account::show();
192     cout << "\tAvailable credit:" << getAvailableCredit();
193 }
194 task7.cpp
195 #include "account.h"
196 #include<iostream>
197 using namespace std;
198 int main() {
199     Date date(2008, 11, 1);
200     SavingsAccount sa1(date, "S3755217", 0.015);
201     SavingsAccount sa2(date, "02342342", 0.015);
202     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
203     sa1.deposit(Date(2008, 11, 5), 5000, "Salary");
204     ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell");
205     sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
206     ca.settle(Date(2008, 12, 1));
207     ca.deposit(Date(2008, 12,1), 2016, "repay the credit");
208     sa1.deposit(Date(2008, 12, 5), 5500, "salary");
209     sa1.settle(Date(2009, 1, 1));
210     sa2.settle(Date(2009, 1, 1));
211     ca.settle(Date(2009, 1, 1));
212     cout << endl;
213     sa1.show(); cout << endl;
214     sa2.show(); cout << endl;
215     ca.show(); cout << endl;
216     cout << "Total: " << Account::getTotal() << endl;
217     return 0;
218 
219 }
View Code

截图:

问题:运用类的派生,提高代码复用性

 

posted on 2024-11-21 13:07  nofear妈  阅读(0)  评论(0编辑  收藏  举报

导航