实验4 类的组合、继承、模板类、标准库
1.实验二:
GradeCalc.hpp
#include<iostream> #include<vector> #include<string> #include<algorithm> #include<numeric> #include<iomanip> using std::vector; using std::string; using std::cin; using std::cout; using std::endl; class GradeCalc : public vector<int> { public: GradeCalc(const string& cname, int size); void input();// 录入成绩 void output() const;//输出成绩 void sort(bool ascending = false);//排序(默认降序) int min() const;//返回最低分 int max() const;//返回最高分 float average() const;//返回平均分 void info();//输出课程成绩信息 private: void compute(); private: string course_name; int n; vector<int>counts = vector<int>(5, 0);//保存各分数段人数 vector<double>rates = vector<double>(5, 0);//保存各分数段比例 }; GradeCalc::GradeCalc(const string& cname, int size) : course_name{ cname }, n{ size } {} void GradeCalc::input() { int grade; for (int i = 0; i < n; ++i) { cin >> grade; this->push_back(grade); } } void GradeCalc::output() const { for (auto ptr = this->begin(); ptr != this->end(); ++ptr) cout << *ptr << " "; cout << endl; } void GradeCalc::sort(bool ascending) { if (ascending) std::sort(this->begin(), this->end()); else std::sort(this->begin(), this->end(), std::greater<int>()); } int GradeCalc::min() const { return *std::min_element(this->begin(), this->end()); } int GradeCalc::max() const { return *std::max_element(this->begin(), this->end()); } float GradeCalc::average() const { return std::accumulate(this->begin(), this->end(), 0) * 1.0 / n; } void GradeCalc::compute() { for (int grade : *this) { if (grade < 60) counts.at(0)++; else if (grade >= 60 && grade < 70) counts.at(1)++; else if (grade >= 70 && grade < 80) counts.at(2)++; else if (grade >= 80 && grade < 90) counts.at(3)++; else if (grade >= 90) counts.at(4)++; } for (int i = 0; i < rates.size(); ++i) rates.at(i) = counts.at(i) * 1.0 / n; } void GradeCalc::info() { cout << "课程名称:\t" << course_name << endl; cout << "排序后成绩: \t"; sort(); output(); cout << "最高分:\t" << max() << endl; cout << "最低分:\t" << min() << endl; cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl; compute(); // 统计各分数段人数、比例 vector<string> tmp{ "[0, 60) ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]" }; for (int i = tmp.size() - 1; i >= 0; --i) cout << tmp[i] << "\t: " << counts[i] << "人\t" << std::fixed << std::setprecision(2) << rates[i] * 100 << "%" << endl; }
test.cpp
#include "GradeCalc.hpp" #include <iomanip> void test() { int n; cout << "输入班级人数: "; cin >> n; GradeCalc c1("OOP", n); cout << "录入成绩: " << endl;; c1.input(); cout << "输出成绩: " << endl; c1.output(); cout << string(20, '*') + "课程成绩信息" + string(20, '*') << endl; c1.info(); } int main() { test(); }
运行结果截图
问题1:
成绩存储在 vector<int>;通过
this
指针;通过 this->push_back(grade)
问题2:
计算百分比,将数据类型改变成浮点型
问题3:
可以判断录入成绩是否合法
2.实验3:
GradeCalc.hpp
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <numeric> #include <iomanip> using std::vector; using std::string; using std::cin; using std::cout; using std::endl; class GradeCalc { public: GradeCalc(const string& cname, int size); void input(); // 录入成绩 void output() const; // 输出成绩 void sort(bool ascending = false); // 排序 (默认降序) int min() const; // 返回最低分 int max() const; // 返回最高分 float average() const; // 返回平均分 void info(); // 输出课程成绩信息 private: void compute(); // 成绩统计 private: string course_name; // 课程名 int n; // 课程人数 vector<int> grades; // 课程成绩 vector<int> counts = vector<int>(5, 0); // 保存各分数段人数([0, 60), [60, 70), [70, 80), [80, 90), [90, 100] vector<double> rates = vector<double>(5, 0); // 保存各分数段比例 }; GradeCalc::GradeCalc(const string& cname, int size) : course_name{ cname }, n{ size } {} void GradeCalc::input() { int grade; for (int i = 0; i < n; ++i) { cin >> grade; grades.push_back(grade); } } void GradeCalc::output() const { for (int grade : grades) cout << grade << " "; cout << endl; } void GradeCalc::sort(bool ascending) { if (ascending) std::sort(grades.begin(), grades.end()); else std::sort(grades.begin(), grades.end(), std::greater<int>()); } int GradeCalc::min() const { return *std::min_element(grades.begin(), grades.end()); } int GradeCalc::max() const { return *std::max_element(grades.begin(), grades.end()); } float GradeCalc::average() const { return std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n; } void GradeCalc::compute() { for (int grade : grades) { if (grade < 60) counts.at(0)++; else if (grade >= 60 && grade < 70) counts.at(1)++; else if (grade >= 70 && grade < 80) counts.at(2)++; else if (grade >= 80 && grade < 90) counts.at(3)++; else if (grade >= 90) counts.at(4)++; } for (int i = 0; i < rates.size(); ++i) rates.at(i) = counts.at(i) * 1.0 / n; } void GradeCalc::info() { cout << "课程名称:\t" << course_name << endl; cout << "排序后成绩: \t"; sort(); output(); cout << "最高分:\t" << max() << endl; cout << "最低分:\t" << min() << endl; cout << "平均分:\t" << std::fixed << std::setprecision(2) << average() << endl; compute(); // 统计各分数段人数、比例 vector<string> tmp{ "[0, 60) ", "[60, 70)", "[70, 80)","[80, 90)", "[90, 100]" }; for (int i = tmp.size() - 1; i >= 0; --i) cout << tmp[i] << "\t: " << counts[i] << "人\t" << std::fixed << std::setprecision(2) << rates[i] * 100 << "%" << endl; }
test.cpp
#include "GradeCalc.hpp" #include <iomanip> void test() { int n; cout << "输入班级人数: "; cin >> n; GradeCalc c1("OOP", n); cout << "录入成绩: " << endl;; c1.input(); cout << "输出成绩: " << endl; c1.output(); cout << string(20, '*') + "课程成绩信息" + string(20, '*') << endl; c1.info(); } int main() { test(); }
运行代码截图
问题1:存储在私有成员变量vector<int> grades;;通过直接访问
grades
问题2:通过grades实现了更加方便的访问
3.实验4:
4.1.cpp
#include <iostream> #include <string> #include <limits> using namespace std; void test1() { string s1, s2; cin >> s1 >> s2; // cin: 从输入流读取字符串, 碰到空白符(空格/回车/Tab)即结束 cout << "s1: " << s1 << endl; cout << "s2: " << s2 << endl; } void test2() { string s1, s2; getline(cin, s1); // getline(): 从输入流中提取字符串,直到遇到换行符 getline(cin, s2); cout << "s1: " << s1 << endl; cout << "s2: " << s2 << endl; } void test3() { string s1, s2; getline(cin, s1, ' '); //从输入流中提取字符串,直到遇到指定分隔符 getline(cin, s2); cout << "s1: " << s1 << endl; cout << "s2: " << s2 << endl; } int main() { cout << "测试1: 使用标准输入流对象cin输入字符串" << endl; test1(); cout << endl; cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "测试2: 使用函数getline()输入字符串" << endl; test2(); cout << endl; cout << "测试3: 使用函数getline()输入字符串, 指定字符串分隔符" << endl; test3(); }
运行结果截图:
问题1:
运行结果截图:
问题1:
忽略输入流cin
中从当前位置开始直到下一个换行符(包括换行符本身)的所有字符 避免前一次输入的换行符或多余字符影响到下一次输入
4.2.cpp
#include <iostream> #include <string> #include <vector> #include <limits> using namespace std; void output(const vector<string> &v) { for(auto &s: v) cout << s << endl; } void test() { int n; while(cout << "Enter n: ", cin >> n) { vector<string> v1; for(int i = 0; i < n; ++i) { string s; cin >> s; v1.push_back(s); } cout << "output v1: " << endl; output(v1); cout << endl; } } int main() { cout << "测试: 使用cin多组输入字符串" << endl; test(); }
运行结果截图
4.3.cpp
#include <iostream> #include <string> #include <vector> #include <limits> using namespace std; void output(const vector<string> &v) { for(auto &s: v) cout << s << endl; } void test() { int n; while(cout << "Enter n: ", cin >> n) { cin.ignore(numeric_limits<streamsize>::max(), '\n'); vector<string> v2; for(int i = 0; i < n; ++i) { string s; getline(cin, s); v2.push_back(s); } cout << "output v2: " << endl; output(v2); cout << endl; } } int main() { cout << "测试: 使用函数getline()多组输入字符串" << endl; test(); }
运行结果截图
忽略输入流中从当前位置开始直到下一个换行符(包括换行符本身)的所有字符
4.实验5:
grm.hpp
#ifndef GRM_HPP #define GRM_HPP template <typename T> class GameResourceManager { private: T resource; public: // 带参数的构造函数,初始化当前资源数量 GameResourceManager(T initialResource) : resource(initialResource) {} // 获取当前的资源数量 T get() const { return resource; } // 更新当前的资源数量(增加、减少) void update(T change) { resource += change; if (resource < 0) { resource = 0; } } }; #endif
test.cpp
#include "grm.hpp" #include <iostream> using std::cout; using std::endl; void test1() { GameResourceManager<float> HP_manager(99.99); cout << "当前生命值: " << HP_manager.get() << endl; HP_manager.update(9.99); cout << "增加9.99生命值后, 当前生命值: " << HP_manager.get() << endl; HP_manager.update(-999.99); cout << "减少999.99生命值后, 当前生命值: " << HP_manager.get() << endl; } void test2() { GameResourceManager<int> Gold_manager(100); cout << "当前金币数量: " << Gold_manager.get() << endl; Gold_manager.update(50); cout << "增加50个金币后, 当前金币数量: " << Gold_manager.get() << endl; Gold_manager.update(-99); cout << "减少99个金币后, 当前金币数量: " << Gold_manager.get() << endl; } int main() { cout << "测试1: 用float类型对类模板GameResourceManager实例化" << endl; test1(); cout << endl; cout << "测试2: 用int类型对类模板GameResourceManager实例化" << endl; test2(); }
运行结果截图
5.实验6:
info.hpp
#ifndef INFO_HPP #define INFO_HPP #include<iostream> #include <string> class Info { private: std::string nickname; std::string contact; std::string city; int n; public: // 带参数的构造函数,用于初始化预约信息 Info(const std::string& _nickname, const std::string& _contact, const std::string& _city, int _n) : nickname(_nickname), contact(_contact), city(_city), n(_n) {} // 显示信息(昵称、联系方式、所在城市、预定参加人数) void display() const { std::cout << "昵称: " << nickname << std::endl; std::cout << "联系方式: " << contact << std::endl; std::cout << "所在城市: " << city << std::endl; std::cout << "预定参加人数: " << n << std::endl; } // 获取预定参加人数 int getN() const { return n; } }; #endif
6.cpp
#include "info.hpp" #include <iostream> #include <vector> #include <string> #include <limits> int main() { // 定义一个const常量capacity用于存放livehouse最多能容纳的听众人数 const int capacity = 100; // 定义一个vector<Info>类对象audience_lst,用于存放线上预约登记的所有听众信息 std::vector<Info> audience_lst; // 当前已预约的人数 int currentCapacity = 0; std::string nickname, contact, city; int n; std::cout << "请输入预约信息(昵称 联系方式 所在城市 预定参加人数,以空格分隔,输入Ctrl+Z或达到场地容量时停止录入):" << std::endl; while (true) { if (!(std::cin >> nickname >> contact >> city >> n)) { // 检测到Ctrl+Z,结束输入 if (std::cin.eof()) { break; } // 输入错误,清除错误状态并忽略当前行剩余字符 std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); continue; } if (currentCapacity + n > capacity) { std::cout << "预定参加人数超过livehouse场地剩余容量,请输入q退出预定,或输入u更新预定信息:"; std::string choice; std::cin >> choice; if (choice == "q") { break; } else if (choice == "u") { std::cout << "请重新输入预约信息(昵称 联系方式 所在城市 预定参加人数,以空格分隔):"; continue; } else { std::cout << "无效选择,请重新输入。" << std::endl; continue; } } Info newInfo(nickname, contact, city, n); audience_lst.push_back(newInfo); currentCapacity += n; if (currentCapacity >= capacity) { std::cout << "已达到场地最大容纳人数,停止预约。" << std::endl; break; } } // 打印输出预约参加livehouse的听众信息 std::cout << "预约参加livehouse的听众信息如下:" << std::endl; for (const auto& info : audience_lst) { info.display(); } return 0; }
运行结果截图
6.实验7:
account.h
#pragma once #include"date.h" #include"accumulator.h" #include<string> using namespace std; class Account { private: string id; double balance; static double total; protected: Account(const Date& date, const string& id); void record(const Date& date, double amount, const string& desc); void error(const string& msg) const; public:const string& getId() { return id; } double getBalance()const { return balance; } static double getTotal() { return total; } void show()const; }; class SavingsAccount :public Account { private: Accumulator acc; double rate; public: SavingsAccount(const Date& date, const string& id, double rate); double getRate() const { return rate; } void deposit(const Date& date, double amount, const string& desc); void withdraw(const Date& date, double amount, const string& desc); void settle(const Date& date); }; class CreditAccount :public Account { private: Accumulator acc; double credit; double rate; double fee; double getDebt()const { double balance = getBalance(); return(balance < 0 ? balance : 0); } public:CreditAccount(const Date& date, const string& id, double credit, double rate, double fee); double getCredit()const { return credit; } double getRate()const { return rate; } double getFee() const { return fee; } double getAvailableCredit()const { if (getBalance() < 0)return credit + getBalance(); else return credit; } void deposit(const Date& date, double amount, const string& desc); void withdraw(const Date& date, double amount, const string& desc); void settle(const Date& date); void show()const; };
accumulator.h
#pragma once #include "date.h" class Accumulator { private: Date lastDate; double value; double sum; public: Accumulator(const Date& date, double value) :lastDate(date), value(value), sum{ 0 } {} double getSum(const Date& date) const { return sum + value * date.distance(lastDate); } void change(const Date& date, double value) { sum = getSum(date); lastDate = date; this->value = value; } void reset(const Date& date, double value) { lastDate = date; this->value; sum = 0; } };
date.h
#pragma once class Date { private: int year; int month; int day; int totalDays; public: Date(int year, int month, int day); int getYear()const { return year; } int getMonth()const { return month; } int getDay()const { return day; } int getMaxDay()const; bool isLeapYear()const { return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; } void show() const; int distance(const Date& date)const { return totalDays - date.totalDays; } };
account.cpp
#include "account.h" #include <cmath> #include<iostream> using namespace std; double Account::total = 0; Account::Account(const Date& date, const string& id) :id(id), balance(0) { date.show(); cout << "\t#" << id << "created" << endl; } void Account::record(const Date& date, double amount, const string& desc) { amount = floor(amount * 100 + 0.5) / 100; balance += amount; total += amount; date.show(); cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl; } void Account::show()const { cout << id << "\tBalance:" << balance; } void Account::error(const string& msg)const { cout << "Error(#" << id << "):" << msg << endl; } SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) :Account(date, id), rate(rate), acc(date, 0) {} void SavingsAccount::deposit(const Date& date, double amount, const string& desc) { record(date, amount, desc); acc.change(date, getBalance()); } void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) { if (amount > getBalance()) { error("not enough money"); } else { record(date, -amount, desc); acc.change(date, getBalance()); } } void SavingsAccount::settle(const Date& date) { double interest = acc.getSum(date) * rate / date.distance(Date(date.getYear() - 1, 1, 1)); if (interest != 0)record(date, interest, "interest"); acc.reset(date, getBalance()); } 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) {} void CreditAccount::deposit(const Date& date, double amount, const string& desc) { record(date, amount, desc); acc.change(date, getDebt()); } void CreditAccount::withdraw(const Date& date, double amount, const string& desc) { if (amount - getBalance() > credit) { error("not enouogh credit"); } else { record(date, -amount, desc); acc.change(date, getDebt()); } } void CreditAccount::settle(const Date& date) { double interest = acc.getSum(date) * rate; if (interest != 0) record(date, interest, "interest"); if (date.getMonth() == 1)record(date, -fee, "annual fee"); acc.reset(date, getDebt()); } void CreditAccount::show()const { Account::show(); cout << "\tAvailable credit:" << getAvailableCredit(); }
date.cpp
#pragma once #include"date.h" #include"accumulator.h" #include<string> using namespace std; class Account { private: string id; double balance; static double total; protected: Account(const Date& date, const string& id); void record(const Date& date, double amount, const string& desc); void error(const string& msg) const; public:const string& getId() { return id; } double getBalance()const { return balance; } static double getTotal() { return total; } void show()const; }; class SavingsAccount :public Account { private: Accumulator acc; double rate; public: SavingsAccount(const Date& date, const string& id, double rate); double getRate() const { return rate; } void deposit(const Date& date, double amount, const string& desc); void withdraw(const Date& date, double amount, const string& desc); void settle(const Date& date); }; class CreditAccount :public Account { private: Accumulator acc; double credit; double rate; double fee; double getDebt()const { double balance = getBalance(); return(balance < 0 ? balance : 0); } public:CreditAccount(const Date& date, const string& id, double credit, double rate, double fee); double getCredit()const { return credit; } double getRate()const { return rate; } double getFee() const { return fee; } double getAvailableCredit()const { if (getBalance() < 0)return credit + getBalance(); else return credit; } void deposit(const Date& date, double amount, const string& desc); void withdraw(const Date& date, double amount, const string& desc); void settle(const Date& date); void show()const; };
7.10.cpp
#include "account.h" #include<iostream> using namespace std; int main() { Date date(2008, 11, 1); SavingsAccount sa1(date, "S3755217", 0.015); SavingsAccount sa2(date, "02342342", 0.015); CreditAccount ca(date, "C5392394", 10000, 0.0005, 50); sa1.deposit(Date(2008, 11, 5), 5000, "Salary"); ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell"); sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323"); ca.settle(Date(2008, 12, 1)); ca.deposit(Date(2008, 12, 1), 2016, "repay the credit"); sa1.deposit(Date(2008, 12, 5), 5500, "salary"); sa1.settle(Date(2009, 1, 1)); sa2.settle(Date(2009, 1, 1)); ca.settle(Date(2009, 1, 1)); cout << endl; sa1.show(); cout << endl; sa2.show(); cout << endl; ca.show(); cout << endl; cout << "Total: " << Account::getTotal() << endl; return 0; }
运行结果截图