实验1
task1.cpp
task1_1.cpp: #include <iostream> using std::cout; using std::endl; // 类A的定义 class A { public: A(int x0, int y0); void display() const; private: int x, y; }; A::A(int x0, int y0): x{x0}, y{y0} { } void A::display() const { cout << x << ", " << y << endl; } // 类B的定义 class B { public: B(double x0, double y0); void display() const; private: double x, y; }; B::B(double x0, double y0): x{x0}, y{y0} { } void B::display() const { cout << x << ", " << y << endl; } void test() { cout << "测试类A: " << endl; A a(3, 4); a.display(); cout << "\n测试类B: " << endl; B b(3.2, 5.6); b.display(); } int main() { test(); } task1_2.cpp: #include <iostream> #include <string> using std::cout; using std::endl; using std::string; // 定义类模板 template<typename T> class X{ public: X(T x0, T y0); void display(); private: T x, y; }; template<typename T> X<T>::X(T x0, T y0): x{x0}, y{y0} { } template<typename T> void X<T>::display() { cout << x << ", " << y << endl; } void test() { cout << "测试1: 类模板X中的抽象类型T用int实例化" << endl; X<int> x1(3, 4); x1.display(); cout << endl; cout << "测试2: 类模板X中的抽象类型T用double实例化" << endl; X<double> x2(3.2, 5.6); x2.display(); cout << endl; cout << "测试3: 类模板X中的抽象类型T用string实例化" << endl; X<string> x3("hello", "oop"); x3.display(); } int main() { test(); } task1_3.cpp: #include <complex> #include <vector> #include <array> int main() { using namespace std; complex<double> x1(5,3); // complex类模板,特化到double类型 vector<int> x2{1, 9, 8, 4}; // vector类模板,特化到int类型 array<int, 4> x3{1,9, 8, 4}; // array类模板,特化到int类型 // 其它略 }View Code
实验2
task2.cpp
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); // 保存各分数段人数([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; 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; } demo2.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(); }View Code
问题1:成绩存储在vector<int>中;用this指针、begin和end;用push_back接口。
问题2:计算平均值;有影响,规定精度。
问题3:可以增加成绩分析功能。
实验3
task3.cpp
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; } demo3.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(); }View Code
问题1:储存在vector<int>grades中;output遍历了grades,其他则使用std库中的对应函数;实验二使用了继承的方法,函数继承自vector。
问题2:直接继承可能会导致接口暴露。
实验4
task4.cpp
task4_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(); } task4_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(); } task4_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(); }View Code
问题1:
分析:作用是清除输入缓冲区的所有内容,直到遇到回车符为止。
问题2:
分析:作用是清除输入缓冲区的所有内容,直到遇到回车符为止。
实验5
task5.cpp
grm.hpp: #pragma once #include<iostream> using namespace std; template<typename T> class GameResourceManager { public: GameResourceManager(T g); T get(); void update(int n); private: T resource; }; template<typename T> GameResourceManager<T>::GameResourceManager(T g) { resource = g; } template<typename T> T GameResourceManager<T>::get() { return resource; } template<typename T> void GameResourceManager<T>::update(int n) { if (resource+n < 0) { resource = 0; } else { resource += n; } } task5.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(); }View Code
实验6
task6.cpp
info.hpp: #pragma once #include<iostream> #include<string> using namespace std; class Info { public: Info() {}; Info(string nickname,string contact,string city,int n); void display(); private: string nickname, contact, city; int n; }; Info::Info(string nickname, string contact, string city, int n) { Info::nickname = nickname; Info::contact = contact; Info::city = city; Info::n = n; } void Info::display() { cout << "-----------------------------" << endl; cout << "昵称:" << nickname <<"\n" << "联系方式(邮箱/手机号):" << contact <<"\n" << "所在城市:" << city <<"\n" << "预定参加人数:" << n << endl; } task6.cpp: #include<iostream> #include"info.hpp" #include<string> #include<vector> const int capacity = 100; using namespace std; vector<Info>audience_list; int main(){ cout << "录入用户预约信息:\n" << endl; string nickname, contact, city; int n,total=0,num=0; label: while (cout << "昵称:", cin >> nickname){ cout << "联系方式(手机号/邮箱):"; cin >> contact; cout << "所在城市:"; cin >> city; cout << "预定参加人数:"; cin >> n;; num = total; total += n; if (total > capacity) { break; } audience_list.push_back(Info(nickname, contact, city, n)); if (total == capacity) { break; } } if (total > capacity) { cout << "对不起,当前只剩 " << capacity - num << " 个位置。" << endl; cout << "1、输入u,更新(update)预定信息。\n"<< "2、输入q,退出预定。" << endl; total=num; char choice; cin >> choice; if (choice == 'u') { goto label; } } cout << endl; cout << "截至目前,一共有" <<total<<"位观众预约。预约听众信息如下:" <<total<< endl; for (auto& i : audience_list) { i.display(); } return 0; }View Code
实验7
tassk7.cpp
1 accumulator.h: 2 #pragma once 3 #ifndef __ACCUMULATOR_H__ 4 #define __ACCUMULATOR_H__ 5 #include "date.h" 6 class Accumulator { 7 private: 8 Date lastDate; 9 double value; 10 double sum; 11 public: 12 Accumulator(const Date& date, double value) 13 : lastDate(date), value(value), sum(0) { } 14 double getSum(const Date& date) const { 15 return sum + value * date.distance(lastDate); 16 } 17 void change(const Date& date, double value) { 18 sum = getSum(date); 19 lastDate = date; this->value = value; 20 } 21 void reset(const Date& date, double value) { 22 lastDate = date; this->value = value; sum = 0; 23 } 24 }; 25 #endif 26 27 account.h: 28 #pragma once 29 #ifndef __ACCOUNT_H__ 30 #define __ACCOUNT_H__ 31 #include "date.h" 32 #include "accumulator.h" 33 #include <string> 34 class Account { 35 private: 36 std::string id; 37 double balance; 38 static double total; 39 protected: 40 Account(const Date& date, const std::string& id); 41 void record(const Date& date, double amount, const std::string& desc); 42 void error(const std::string& msg) const; 43 public: 44 const std::string& getId() const { return id; } 45 double getBalance() const { return balance; } 46 static double getTotal() { return total; } 47 void show() const; 48 }; 49 class SavingsAccount : public Account { 50 private: 51 Accumulator acc; 52 double rate; 53 public: 54 SavingsAccount(const Date& date, const std::string& id, double rate); 55 double getRate() const { return rate; } 56 void deposit(const Date& date, double amount, const std::string& desc); 57 void withdraw(const Date& date, double amount, const std::string& desc); 58 void settle(const Date& date); 59 }; 60 class CreditAccount : public Account { 61 private: 62 Accumulator acc; 63 double credit; 64 double rate; 65 double fee; 66 double getDebt() const { 67 double balance = getBalance(); 68 return (balance < 0 ? balance : 0); 69 } 70 public: 71 CreditAccount(const Date& date, const std::string& id, double credit, double rate, double fee); 72 double getCredit() const { return credit; } 73 double getRate() const { return rate; } 74 double getFee() const { return fee; } 75 double getAvailableCredit() const { 76 if (getBalance() < 0) 77 return credit + getBalance(); 78 else 79 return credit; 80 } 81 void deposit(const Date& date, double amount, const std::string& desc); 82 void withdraw(const Date& date, double amount, const std::string& desc); 83 void settle(const Date& date); 84 void show() const; 85 }; 86 #endif 87 88 date.h: 89 #pragma once 90 class Date { 91 private: 92 int year; 93 int month; 94 int day; 95 int totalDays; 96 public: 97 Date(int year, int month, int days); 98 int getYear()const { return year; } 99 int getDay()const { return day; } 100 int getMonth()const { return month; } 101 int getMaxDay()const; 102 bool isLeapYear()const { 103 return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 104 } 105 void show()const; 106 int distance(const Date& date)const { 107 return totalDays - date.totalDays; 108 } 109 }; 110 111 date.cpp: 112 #include"date.h" 113 #include<iostream> 114 #include<cstdlib> 115 using namespace std; 116 namespace { 117 const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 }; 118 } 119 Date::Date(int year, int month, int day) :year(year), month(month), day(day) { 120 if (day <= 0 || day > getMaxDay()) { 121 cout << "Invalid date:"; 122 show(); 123 cout << endl; 124 exit(1); 125 } 126 int years = year - 1; 127 totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day; 128 if (isLeapYear() && month > 2) 129 totalDays++; 130 } 131 int Date::getMaxDay()const { 132 if (isLeapYear() && month >= 2) 133 return 29; 134 else 135 return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1]; 136 } 137 void Date::show()const { 138 cout << getYear() << "-" << getMonth() << "-" << getDay(); 139 } 140 141 account.cpp: 142 #include "account.h" 143 #include <cmath> 144 #include <iostream> 145 using namespace std; 146 double Account::total = 0; 147 Account::Account(const Date& date, const string& id) 148 : id(id), balance(0) { 149 date.show(); cout << "\t#" << id << " created" << endl; 150 } 151 void Account::record(const Date& date, double amount, const string& desc) { 152 amount = floor(amount * 100 + 0.5) / 100; 153 balance += amount; total += amount; 154 date.show(); 155 cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl; 156 } 157 void Account::show() const { cout << id << "\tBalance: " << balance; } 158 void Account::error(const string& msg) const { 159 cout << "Error(#" << id << "): " << msg << endl; 160 } 161 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) 162 : Account(date, id), rate(rate), acc(date, 0) { } 163 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) { 164 record(date, amount, desc); 165 acc.change(date, getBalance()); 166 } 167 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) { 168 if (amount > getBalance()) { 169 error("not enough money"); 170 } 171 else { 172 record(date, -amount, desc); 173 acc.change(date, getBalance()); 174 } 175 } 176 void SavingsAccount::settle(const Date& date) { 177 double interest = acc.getSum(date) * rate 178 / date.distance(Date(date.getYear() - 1, 1, 1)); 179 if (interest != 0) record(date, interest, "interest"); 180 acc.reset(date, getBalance()); 181 } 182 183 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee) 184 : Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) { } 185 void CreditAccount::deposit(const Date& date, double amount, const string& desc) { 186 record(date, amount, desc); 187 acc.change(date, getDebt()); 188 } 189 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) { 190 if (amount - getBalance() > credit) { 191 error("not enough credit"); 192 } 193 else { 194 record(date, -amount, desc); 195 acc.change(date, getDebt()); 196 } 197 } 198 void CreditAccount::settle(const Date& date) { 199 double interest = acc.getSum(date) * rate; 200 if (interest != 0) record(date, interest, "interest"); 201 if (date.getMonth() == 1) 202 record(date, -fee, "annual fee"); 203 acc.reset(date, getDebt()); 204 } 205 void CreditAccount::show() const { 206 Account::show(); 207 cout << "\tAvailable credit:" << getAvailableCredit(); 208 } 209 210 7_10.cpp: 211 #include "account.h" 212 #include <iostream> 213 using namespace std; 214 int main() { 215 Date date(2008, 11, 1); 216 SavingsAccount sa1(date, "S3755217", 0.015); 217 SavingsAccount sa2(date, "02342342", 0.015); 218 CreditAccount ca(date, "C5392394", 10000, 0.0005, 50); 219 sa1.deposit(Date(2008, 11, 5), 5000, "salary"); 220 ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell"); 221 sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323"); 222 ca.settle(Date(2008, 12, 1)); 223 ca.deposit(Date(2008, 12, 1), 2016, "repay the credit"); 224 sa1.deposit(Date(2008, 12, 5), 5500, "salary"); 225 sa1.settle(Date(2009, 1, 1)); 226 sa2.settle(Date(2009, 1, 1)); 227 ca.settle(Date(2009, 1, 1)); 228 cout << endl; 229 sa1.show(); cout << endl; 230 sa2.show(); cout << endl; 231 ca.show(); cout << endl; 232 cout << "Total: " << Account::getTotal() << endl; 233 return 0; 234 }View Code
标签:std,const,组合,继承,void,int,date,include,模板 From: https://www.cnblogs.com/Altairsss/p/18553038