实验4 C++
任务2:
GradeCalc.cpp
1 #pragma once 2 #include <iostream> 3 #include <vector> 4 #include <string> 5 #include <algorithm> 6 #include <numeric> 7 #include <iomanip> 8 9 using std::vector; 10 using std::string; 11 using std::cin; 12 using std::cout; 13 using std::endl; 14 15 class GradeCalc: public vector<int> { 16 public: 17 GradeCalc(const string &cname, int size); 18 void input(); // 录入成绩 19 void output() const; // 输出成绩 20 void sort(bool ascending = false); // 排序 (默认降序) 21 int min() const; // 返回最低分 22 int max() const; // 返回最高分 23 float average() const; // 返回平均分 24 void info(); // 输出课程成绩信息 25 26 private: 27 void compute(); // 成绩统计 28 29 private: 30 string course_name; // 课程名 31 int n; // 课程人数 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 this->push_back(grade); 44 } 45 } 46 47 void GradeCalc::output() const { 48 for(auto ptr = this->begin(); ptr != this->end(); ++ptr) 49 cout << *ptr << " "; 50 cout << endl; 51 } 52 53 void GradeCalc::sort(bool ascending) { 54 if(ascending) 55 std::sort(this->begin(), this->end()); 56 else 57 std::sort(this->begin(), this->end(), std::greater<int>()); 58 } 59 60 int GradeCalc::min() const { 61 return *std::min_element(this->begin(), this->end()); 62 } 63 64 int GradeCalc::max() const { 65 return *std::max_element(this->begin(), this->end()); 66 } 67 68 float GradeCalc::average() const { 69 return std::accumulate(this->begin(), this->end(), 0) * 1.0 / n; 70 } 71 72 void GradeCalc::compute() { 73 for(int grade: *this) { 74 if(grade < 60) 75 counts.at(0)++; 76 else if(grade >= 60 && grade < 70) 77 counts.at(1)++; 78 else if(grade >= 70 && grade < 80) 79 counts.at(2)++; 80 else if(grade >= 80 && grade < 90) 81 counts.at(3)++; 82 else if(grade >= 90) 83 counts.at(4)++; 84 } 85 86 for(int i = 0; i < rates.size(); ++i) 87 rates.at(i) = counts.at(i) * 1.0 / n; 88 } 89 90 void GradeCalc::info() { 91 cout << "课程名称:\t" << course_name << endl; 92 cout << "排序后成绩: \t"; 93 sort(); output(); 94 cout << "最高分:\t" << max() << endl; 95 cout << "最低分:\t" << min() << endl; 96 cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl; 97 98 compute(); // 统计各分数段人数、比例 99 100 vector<string> tmp{"[0, 60) ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"}; 101 for(int i = tmp.size()-1; i >= 0; --i) 102 cout << tmp[i] << "\t: " << counts[i] << "人\t" 103 << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 104 }
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:成绩存储在其基类vector类中;通过public继承方式继承的vector类中的接口访问每一个成绩;通过vector类中的push_back接口存入。
问题2:计算vector容器中存储所有元素的平均值;有影响,因为不加1.0时在整除运算会失去小数部分。
问题3:当班级人数输入为0时会导致除数为0,从而发生错误,应该限制输入格式。
任务3:
GradeCalc.hpp
1 #pragma once 2 #include <iostream> 3 #include <vector> 4 #include <string> 5 #include <algorithm> 6 #include <numeric> 7 #include <iomanip> 8 9 using std::vector; 10 using std::string; 11 using std::cin; 12 using std::cout; 13 using std::endl; 14 15 class GradeCalc { 16 public: 17 GradeCalc(const string &cname, int size); 18 void input(); // 录入成绩 19 void output() const; // 输出成绩 20 void sort(bool ascending = false); // 排序 (默认降序) 21 int min() const; // 返回最低分 22 int max() const; // 返回最高分 23 float average() const; // 返回平均分 24 void info(); // 输出课程成绩信息 25 26 private: 27 void compute(); // 成绩统计 28 29 private: 30 string course_name; // 课程名 31 int n; // 课程人数 32 vector<int> grades; // 课程成绩 33 vector<int> counts = vector<int>(5, 0); // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100] 34 vector<double> rates = vector<double>(5, 0); // 保存各分数段比例 35 }; 36 37 GradeCalc::GradeCalc(const string &cname, int size): course_name{cname}, n{size} {} 38 39 void GradeCalc::input() { 40 int grade; 41 42 for(int i = 0; i < n; ++i) { 43 cin >> grade; 44 grades.push_back(grade); 45 } 46 } 47 48 void GradeCalc::output() const { 49 for(int grade: grades) 50 cout << grade << " "; 51 cout << endl; 52 } 53 54 void GradeCalc::sort(bool ascending) { 55 if(ascending) 56 std::sort(grades.begin(), grades.end()); 57 else 58 std::sort(grades.begin(), grades.end(), std::greater<int>()); 59 60 } 61 62 int GradeCalc::min() const { 63 return *std::min_element(grades.begin(), grades.end()); 64 } 65 66 int GradeCalc::max() const { 67 return *std::max_element(grades.begin(), grades.end()); 68 } 69 70 float GradeCalc::average() const { 71 return std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n; 72 } 73 74 void GradeCalc::compute() { 75 for(int grade: grades) { 76 if(grade < 60) 77 counts.at(0)++; 78 else if(grade >= 60 && grade < 70) 79 counts.at(1)++; 80 else if(grade >= 70 && grade < 80) 81 counts.at(2)++; 82 else if(grade >= 80 && grade < 90) 83 counts.at(3)++; 84 else if(grade >= 90) 85 counts.at(4)++; 86 } 87 88 for(int i = 0; i < rates.size(); ++i) 89 rates.at(i) = counts.at(i) *1.0 / n; 90 } 91 92 void GradeCalc::info() { 93 cout << "课程名称:\t" << course_name << endl; 94 cout << "排序后成绩: \t"; 95 sort(); output(); 96 cout << "最高分:\t" << max() << endl; 97 cout << "最低分:\t" << min() << endl; 98 cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl; 99 100 compute(); // 统计各分数段人数、比例 101 102 vector<string> tmp{"[0, 60) ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]"}; 103 for(int i = tmp.size()-1; i >= 0; --i) 104 cout << tmp[i] << "\t: " << counts[i] << "人\t" 105 << std::fixed << std::setprecision(2) << rates[i]*100 << "%" << endl; 106 }
task3.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:存储在GaradeCalc类的私有成员vector<int> grade中,直接在类内部访问grade。
问题2:通过继承基类可以访问基类中的接口以方便操作。
任务4:
task4_1.cpp
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 }
运行结果:
task4_2.cpp
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 }
运行结果:
task4_3.cpp
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 }
运行结果:
问题1:用 cin.ignore()忽略换行符,使getline() 能正确读取后续用户输入的字符串。
问题2:用 cin.ignore()忽略换行符,使循环能在停止输入(即^Z) 时正确终止。
任务5:
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 resource; 10 public: 11 GameResourceManager(T n) : resource{n} {} 12 T get() const; 13 void update(T n); 14 }; 15 16 template<typename T> 17 T GameResourceManager<T>::get() const{ 18 return resource; 19 } 20 21 template<typename T> 22 void GameResourceManager<T>::update(T n) { 23 if(resource + n > 0) 24 resource += n; 25 else 26 resource = 0; 27 }
task5.cpp
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 }
运行结果:
任务6:
Info.hpp
1 #pragma once 2 #include <iostream> 3 #include <string> 4 #include <iomanip> 5 6 using namespace std; 7 8 class Info { 9 private: 10 string nickname; 11 string contact; 12 string city; 13 public: 14 int n; 15 public: 16 Info(string nn , string ct , string c , int N) : nickname{nn} , contact{ct} , city{c} , n{N} {} 17 void display() const; 18 }; 19 20 void Info::display() const { 21 cout << left << setw(16) << "昵称:" << left << setw(16) << nickname << endl; 22 cout << left << setw(16) << "联系方式:" << left << setw(16) << contact << endl; 23 cout << left << setw(16) << "所在城市:" << left << setw(16) << city << endl; 24 cout << left << setw(16) << "预定人数:" << left << setw(16) << n << endl; 25 }
task6.cpp
1 #include "Info.hpp" 2 #include <vector> 3 4 using namespace std; 5 6 void test() { 7 string nn , ct , c; 8 int N , count = 0 , n; 9 const int capacity = 100; 10 vector<Info> audience_list; 11 char choose; 12 13 cout << "录入用户预约信息:" << endl; 14 cout << endl; 15 cout << left << setw(16) << "昵称" << left << setw(32) << "联系方式(邮箱/手机号)" << left << setw(16) << "所在城市" << left << setw(16) << "预定参加人数" <<endl; 16 while(count != capacity) { 17 cin >> nn; 18 if(nn == "stop") 19 break; 20 cin >> ct >> c >> N ; 21 Info I(nn , ct , c , N); 22 if(count < capacity) { 23 audience_list.push_back(I); 24 count += N; 25 } 26 if(count > capacity){ 27 count -= N; 28 audience_list.pop_back(); 29 cout << "对不起,只剩" << capacity - count << "个位置." << endl; 30 cout << "1. 输入u,更新(update)预定信息" << endl; 31 cout << "2. 输入q,退出预定" << endl; 32 cout << "你的选择: "; 33 cin >> choose; 34 if(choose == 'u') { 35 cout << "请重新输入预定信息:" << endl; 36 cin >> nn >> ct >> c >> N ; 37 Info I(nn , ct , c ,N); 38 audience_list.push_back(I); 39 count += N; 40 } 41 else if(choose == 'q') 42 break; 43 } 44 } 45 cout << endl; 46 cout << "截至目前,一共有" << count << "位听众预约。预约听众信息如下:" << endl; 47 cout << "-----------------------------------" << endl; 48 for(auto i : audience_list) { 49 i.display(); 50 cout << "-----------------------------------" << endl; 51 } 52 } 53 54 int main() { 55 test(); 56 }
运行结果:
1.
2.
任务7:
date.h
1 #pragma once 2 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 };
date.cpp
1 #include"date.h" 2 #include<iostream> 3 #include<cstdlib> 4 5 using namespace std; 6 7 namespace { 8 const int DAYS_BEFIRE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304 ,334,365 }; 9 } 10 Date::Date(int year, int month, int day) :year(year), month(month), day(day) { 11 if (day<= 0 || day>getMaxDay()) { 12 cout<<"Invalid date: "; 13 show(); 14 cout<<endl; 15 exit(1); 16 } 17 int years=year-1; 18 totalDays=years*365+years/4-years/100+years/400+DAYS_BEFIRE_MONTH[month-1]+day; 19 if (isLeapYear() && month>2) totalDays++; 20 } 21 int Date::getMaxDay() const { 22 if (isLeapYear() &&month==2) 23 return 29; 24 else return DAYS_BEFIRE_MONTH[month]-DAYS_BEFIRE_MONTH[month-1]; 25 } 26 void Date::show()const { 27 cout<<getYear()<<"-"<<getMonth()<<"-"<<getDay(); 28 }
accumulator.h
1 #include "date.h" 2 class Accumulator { 3 private: 4 Date lastDate; 5 double value; 6 double sum; 7 public: 8 Accumulator(const Date &date , double value) : lastDate{date} , value{value} , sum{0} {} 9 double getSum(const Date &date) const { 10 return sum + value * date.distance(lastDate); 11 } 12 void change(const Date &date , double value) { 13 sum = getSum(date); 14 lastDate = date; 15 this->value = value; 16 } 17 void reset(const Date &date , double value) { 18 lastDate = date; 19 this->value = value; 20 sum = 0; 21 } 22 };
account.h
1 #include "date.h" 2 #include "accumulator.h" 3 #include <string> 4 5 using namespace std; 6 7 class Account { 8 private: 9 string id; 10 double balance; 11 static double total; 12 protected: 13 Account(const Date &date , const string &id); 14 void record(const Date &date , double amount , const string &desc); 15 void error(const string &msg) const; 16 public: 17 const string getId() const {return id;} 18 double getBalance() const {return balance;} 19 static double getTotal() {return total;} 20 void show() const; 21 }; 22 class SavingsAccount:public Account { 23 private: 24 Accumulator acc; 25 double rate; 26 public: 27 SavingsAccount(const Date& date , const string& id , double rate); 28 double getRate() const {return rate;} 29 void deposit(const Date& date , double amount , const string& desc); 30 void withdraw(const Date& date , double amount , const string& desc); 31 void settle(const Date& date); 32 }; 33 class CreditAccount :public Account { 34 private: 35 Accumulator acc; 36 double credit; 37 double rate; 38 double fee; 39 double getDebt() const { 40 double balance = getBalance(); 41 return(balance < 0 ? balance : 0); 42 } 43 public:CreditAccount(const Date& date , const string& id , double credit , double rate , double fee); 44 double getCredit() const {return credit;} 45 double getRate() const {return rate;} 46 double getFee() const {return fee;} 47 double getAvailableCredit() const { 48 if (getBalance() < 0) return credit + getBalance(); 49 else return credit; 50 } 51 void deposit(const Date& date , double amount , const string& desc); 52 void withdraw(const Date& date , double amount , const string& desc); 53 void settle(const Date& date); 54 void show() const; 55 };
account.cpp
1 #include "account.h" 2 #include <cmath> 3 #include<iostream> 4 using namespace std; 5 double Account::total = 0; 6 Account::Account(const Date& date, const string& id) :id(id), balance(0) { 7 date.show(); 8 cout << "\t#" << id << "created" << endl; 9 } 10 void Account::record(const Date& date, double amount, const string& desc) { 11 amount = floor(amount * 100 + 0.5) / 100; 12 balance += amount; 13 total += amount; 14 date.show(); 15 cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl; 16 } 17 void Account::show() const { cout << id << "\tBalance:" << balance; } 18 void Account::error(const string& msg) const { 19 cout << "Error(#" << id << "):" << msg << endl; 20 } 21 SavingsAccount::SavingsAccount(const Date&date,const string &id,double rate):Account(date,id),rate(rate),acc(date,0){} 22 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) { 23 record(date, amount, desc); 24 acc.change(date, getBalance()); 25 } 26 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) { 27 if (amount > getBalance()) { 28 error("not enough money"); 29 } 30 else { 31 record(date, -amount, desc); 32 acc.change(date, getBalance()); 33 } 34 } 35 void SavingsAccount::settle(const Date& date) { 36 double interest = acc.getSum(date) * rate/date.distance(Date(date.getYear()-1,1,1)); 37 if (interest != 0)record(date, interest, "interest"); 38 acc.reset(date, getBalance()); 39 } 40 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){} 41 void CreditAccount::deposit(const Date& date, double amount, const string& desc) { 42 record(date, amount, desc); 43 acc.change(date, getDebt()); 44 } 45 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) { 46 if (amount - getBalance() > credit) { 47 error("not enouogh credit"); 48 } 49 else { 50 record(date, -amount, desc); 51 acc.change(date, getDebt()); 52 } 53 } 54 void CreditAccount::settle(const Date& date) { 55 double interest = acc.getSum(date) * rate; 56 if (interest != 0) record(date, interest, "interest"); 57 if (date.getMonth() == 1)record(date, -fee, "annual fee"); 58 acc.reset(date, getDebt()); 59 } 60 void CreditAccount::show() const { 61 Account::show(); 62 cout << "\tAvailable credit:" << getAvailableCredit(); 63 }
7_10.cpp
1 #include "account.h" 2 #include<iostream> 3 using namespace std; 4 int main() { 5 Date date(2008, 11, 1); 6 SavingsAccount sa1(date, "S3755217", 0.015); 7 SavingsAccount sa2(date, "02342342", 0.015); 8 CreditAccount ca(date, "C5392394", 10000, 0.0005, 50); 9 sa1.deposit(Date(2008, 11, 5), 5000, "Salary"); 10 ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell"); 11 sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323"); 12 ca.settle(Date(2008, 12, 1)); 13 ca.deposit(Date(2008, 12,1), 2016, "repay the credit"); 14 sa1.deposit(Date(2008, 12, 5), 5500, "salary"); 15 sa1.settle(Date(2009, 1, 1)); 16 sa2.settle(Date(2009, 1, 1)); 17 ca.settle(Date(2009, 1, 1)); 18 cout << endl; 19 sa1.show(); cout << endl; 20 sa2.show(); cout << endl; 21 ca.show(); cout << endl; 22 cout << "Total: " << Account::getTotal() << endl; 23 return 0; 24 }
运行结果:
总结:
1. 定义了一个基类account,继承基类得到了两个派生类SavingAccounts和CreditAccounts。
2.重新定义了一个类accumulator用于计算银行账户存款的积累.