1.实验任务1
1 #include <iostream> 2 3 using std::cout; 4 using std::endl; 5 6 // 类A的定义 7 class A { 8 public: 9 A(int x0, int y0); 10 void display() const; 11 12 private: 13 int x, y; 14 }; 15 16 A::A(int x0, int y0): x{x0}, y{y0} { 17 } 18 19 void A::display() const { 20 cout << x << ", " << y << endl; 21 } 22 23 // 类B的定义 24 class B { 25 public: 26 B(double x0, double y0); 27 void display() const; 28 29 private: 30 double x, y; 31 }; 32 33 B::B(double x0, double y0): x{x0}, y{y0} { 34 } 35 36 void B::display() const { 37 cout << x << ", " << y << endl; 38 } 39 40 void test() { 41 cout << "测试类A: " << endl; 42 A a(3, 4); 43 a.display(); 44 45 cout << "\n测试类B: " << endl; 46 B b(3.2, 5.6); 47 b.display(); 48 } 49 50 int main() { 51 test(); 52 }
1 #include <iostream> 2 #include <string> 3 4 using std::cout; 5 using std::endl; 6 using std::string; 7 8 // 定义类模板 9 template<typename T> 10 class X{ 11 public: 12 X(T x0, T y0); 13 void display(); 14 15 private: 16 T x, y; 17 }; 18 19 template<typename T> 20 X<T>::X(T x0, T y0): x{x0}, y{y0} { 21 } 22 23 template<typename T> 24 void X<T>::display() { 25 cout << x << ", " << y << endl; 26 } 27 28 29 void test() { 30 cout << "测试1: 类模板X中的抽象类型T用int实例化" << endl; 31 X<int> x1(3, 4); 32 x1.display(); 33 34 cout << endl; 35 36 cout << "测试2: 类模板X中的抽象类型T用double实例化" << endl; 37 X<double> x2(3.2, 5.6); 38 x2.display(); 39 40 cout << endl; 41 42 cout << "测试3: 类模板X中的抽象类型T用string实例化" << endl; 43 X<string> x3("hello", "oop"); 44 x3.display(); 45 } 46 47 int main() { 48 test(); 49 }
1 #include <complex> 2 #include <vector> 3 #include <array> 4 5 int main() { 6 using namespace std; 7 8 complex<double> x1(5,3); // complex类模板,特化到double类型 9 vector<int> x2{1, 9, 8, 4}; // vector类模板,特化到int类型 10 array<int, 4> x3{1,9, 8, 4}; // array类模板,特化到int类型 11 // 其它略 12 }
2.实验任务2
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 }
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<int>中,派生类方法sort, min, max, average, output通过this指针访问。input 方法通过 this->push_back(grade) 接口将成绩存入对象。
问题2:计算平均值。去掉*1.0后,重新编译和运行,代码很可能会得到错误的结果。*1.0后确保计算结果为浮点数,从而避免求平均值时小数部分的丢失。
问题3:input输入的数据没有合法判定。
3.实验任务3
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 }
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<int> grades
中。
组合类方法sort
, min
, max
, average
, output
都需要访问这些成绩,它们通过直接访问grades
向量来实现。
4.实验任务4
#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:清空缓冲区的内容,消除上一次输入对下一次输入的影响。
#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(); }
#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(); }
问题2:清空缓冲区的内容,消除上一次输入对下一次输入的影响。
5.实验任务5
1 #include<iostream> 2 using namespace std; 3 template<typename T> 4 class GameResourceManager { 5 public: 6 GameResourceManager(T hp):HP(hp){} 7 T get(){ 8 return HP; 9 } 10 void update(T data){ 11 HP+=data; 12 } 13 private: 14 T HP; 15 };
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.实验任务6
#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(std::string nickname, std::string contact, std::string city, int n); void display() const; }; #endif
#include "info.hpp" Info::Info(std::string nickname, std::string contact, std::string city, int n) : nickname(nickname), contact(contact), city(city), n(n) {} void Info::display() const { std::cout << "昵称: " << nickname << std::endl; std::cout << "联系方式: " << contact << std::endl; std::cout << "所在城市: " << city << std::endl; std::cout << "预定参加人数: " << n << std::endl; }
#include <iostream> #include <vector> #include "info.hpp" const int capacity = 100; int main() { std::vector<Info> audience_list; int current_capacity = 0; std::cout << "开始录入用户预约信息:" << std::endl; while (true) { if (current_capacity >= capacity) { std::cout << "场地已满,无法继续预约。" << std::endl; break; } std::string nickname, contact, city; int num_attendees; std::cout << "昵称:"; std::cin >> nickname; if (nickname == "q") { break; } std::cout << "联系方式:"; std::cin >> contact; std::cout << "所在城市:"; std::cin >> city; std::cout << "预定参加人数:"; std::cin >> num_attendees; if (current_capacity + num_attendees > capacity) { std::cout << "超出场地剩余容量,剩余容量:" << (capacity - current_capacity) << std::endl; std::cout << "输入'u'更新预约信息,输入'q'退出:"; std::string choice; std::cin >> choice; if (choice == "q") { break; } else if (choice == "u") { std::cout << "重新输入预约信息:" << std::endl; std::cout << "昵称:"; std::cin >> nickname; std::cout << "联系方式:"; std::cin >> contact; std::cout << "所在城市:"; std::cin >> city; std::cout << "预定参加人数:"; std::cin >> num_attendees; } } Info new_info(nickname, contact, city, num_attendees); audience_list.push_back(new_info); current_capacity += num_attendees; } std::cout << "截至目前,共有 " << current_capacity << " 人预约,预约信息如下:" << std::endl; for (const Info& info : audience_list) { info.display(); std::cout << "----------------------------" << std::endl; } return 0; }
7.实验任务7
#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; } };
#include"date.h" #include<iostream> #include<cstdlib> using namespace std; namespace { const int DAYS_BEFIRE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304 ,334,365 }; } Date::Date(int year, int month, int day) :year(year), month(month), day(day) { if (day <= 0 || day > getMaxDay()) { cout << "Invalid date: "; show(); cout << endl; exit(1); } int years = year - 1; totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFIRE_MONTH[month - 1] + day; if (isLeapYear() && month > 2) totalDays++; } int Date::getMaxDay()const { if (isLeapYear() && month == 2) return 29; else return DAYS_BEFIRE_MONTH[month] - DAYS_BEFIRE_MONTH[month - 1]; } void Date::show()const { cout << getYear() << "-" << getMonth() << "-" << getDay(); }
#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; } };
#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(); }
#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; }
#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; };