Task2:
1 Gradecalc.cpp: 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 } 105 task2.hpp: 106 #include "GradeCalc.hpp" 107 #include <iomanip> 108 109 void test() { 110 int n; 111 cout << "输入班级人数: "; 112 cin >> n; 113 114 GradeCalc c1("OOP", n); 115 116 cout << "录入成绩: " << endl;; 117 c1.input(); 118 cout << "输出成绩: " << endl; 119 c1.output(); 120 121 cout << string(20, '*') + "课程成绩信息" + string(20, '*') << endl; 122 c1.info(); 123 } 124 125 int main() { 126 test(); 127 }task2
问题1:
成绩存储在从vector<int>继承而来的容器中;sort方法通过begin()和end()函数就能访问到存储成绩的容器中的每个元素;min方法使用this->begin()和this->end()作为迭代器范围传递给std::min_element函数,以此来遍历存储成绩的容器中的每个元素;max方法与min方法类似;average方法通过this->begin()和this->end()指定要累加的元素范围,也就是存储成绩的容器中的所有成绩元素,然后再除以学生人数n得到平均分;output方法通过一个循环遍历成绩容器。
问题2:
在代码的line68处,分母n的功能是用于计算各分数段人数占总人数的比例;
如果去掉乘以1.0的代码,重新编译和运行,结果会有影响。在原来的代码中,counts.at(i)是int类型,n也是int类型,当进行除法运算counts.at(i) / n时,如果不进行类型转换(乘以1.0就是将其中一个操作数转换为double类型),结果会按照整数除法规则进行计算,即只保留整数部分,小数部分会被截断。
乘以1.0后,会将其中一个操作数隐式转换为double类型,使得除法运算按照浮点数除法规则进行,能得到正确的比例值,保留小数部分,符合统计各分数段比例的需求。
问题3:
在input方法中,没有对用户输入的成绩进行有效性验证。
目前GradeCalc类只考虑了单一课程的成绩统计。在实际应用场景中,可能需要同时处理多门课程的成绩情况。
程序运行结束后,所有输入的成绩数据和计算得到的统计信息都会丢失。
Task3:
1 复制代码 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 }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:成绩存储在std::vector<int>这个容器中。min、max、sort、average、output是通过std::vector<int>提供的迭代器接口访问每个成绩。
问题2:类的私有成员变量(如grades
、counts
、rates
等)被隐藏在类的内部,外部代码无法直接访问和修改这些数据,只能通过类提供的公有方法来间接操作。这样可以保证数据的安全性和一致性,防止外部代码无意或恶意地篡改数据,使得程序的行为更加可预测和稳定。
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 }1
问题1:
清空输入缓冲区中剩余的字符,特别是换行符等可能影响后续getline
函数正确读取的字符。
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 }2
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 }3
问题2:清空输入缓冲区中剩余的字符,特别是在通过cin >> n
读取完整数n
后,将可能留在输入缓冲区中的换行符(以及其他可能残留的字符)清除掉。、
Task5:
1 #ifndef GRM_HPP 2 #define GRM_HPP 3 4 template <typename T> 5 class GameResourceManager { 6 private: 7 T resource; 8 9 public: 10 // 带参数的构造函数,初始化当前资源数量 11 GameResourceManager(T initialResource) : resource(initialResource) {} 12 13 // 获取当前的资源数量 14 T get() const { 15 return resource; 16 } 17 18 // 更新当前的资源数量(增加、减少) 19 // 当资源数量减少到<0时,则归0 20 void update(T change) { 21 resource += change; 22 if (resource < 0) { 23 resource = 0; 24 } 25 } 26 }; 27 28 #endifgrm.hpp
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 }task5.cpp
Task6:
1 #pragma once 2 #include <iostream> 3 using namespace std; 4 class info { 5 private: 6 string nickname; 7 string contact; 8 string city; 9 int n; 10 public: 11 info(string nickname, string contact, string city, int n) { 12 this->nickname = nickname; 13 this->contact = contact; 14 this->city = city; 15 this->n = n; 16 } 17 void display() { 18 cout << "昵称: " << nickname << endl; 19 cout << "联系方式:" << contact << endl; 20 cout << "所在城市:" << city << endl; 21 cout << "预定人数:" << n << endl; 22 cout << string(70, '-') << endl; 23 } 24 };info
1 #include"info.hpp" 2 #include <vector> 3 using namespace std; 4 int main() { 5 const int capacity = 100; 6 vector<info>audience_lst; 7 int capacity1 = 0; 8 string nickname; 9 string contact; 10 string city; 11 int n; 12 cout << "昵称" + string(5, ' ') + "联系方式(邮箱/手机号)" + string(5, ' ') + "所在城市" + string(5, ' ') + "预定参加人数\n"; 13 while (cin >> nickname>>contact>>city>>n) { 14 cin.ignore(numeric_limits<streamsize>::max(), '\n'); 15 capacity1 += n; 16 if (capacity1 > capacity) { 17 capacity1 -= n; 18 string choose; 19 cout << "对不起,只剩下" << capacity - capacity1 << "个位置.\n" 20 << "1.输入u,更新(update)预定信息\n" 21 << "2.输入q,退出预定\n" 22 << "你的选择:"; 23 cin >> choose; 24 if (choose == "u") { 25 cout << "请重新输入预定信息:\n"; 26 continue; 27 } 28 else 29 { 30 break; 31 } 32 } 33 info livehouse(nickname, contact, city, n); 34 audience_lst.push_back(livehouse); 35 if (capacity1 == capacity) { break; } 36 } 37 cout << "截至目前,一共有" << capacity1 << "位听众预约。预约听众的信息如下:\n"; 38 cout << string(70, '-') << endl; 39 for (auto& i : audience_lst) { 40 i.display(); 41 } 42 return 0; 43 }View Code
Task7:
1 #ifndef __DATE_H__ 2 #define __DATE_H__ 3 4 class Date { 5 private: 6 int year; //年 7 int month; //月 8 int day; //日 9 int totalDays; //该日期是从公元元年1月1日开始的第几天 10 public: 11 Date(int year, int month, int day); //用年、月、日构造日期 12 int getYear() const { return year; } 13 int getMonth() const { return month; } 14 int getDay() const { return day; } 15 int getMaxDay() const; 16 bool isLeapYear() const { 17 return year % 4 == 0 && year % 100 != 0 || year % 400 == 0; 18 } 19 void show() const; 20 //计算两个日期之间相差多少天 21 int distance(const Date& date) const { 22 return totalDays - date.totalDays; 23 } 24 }; 25 #endifdate.h
#include "date.h" #include <iostream> #include <cstdlib> using namespace std; //命名空间使下面的定义只在当前文件中有效 namespace { //存储平年中的某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项 const int DAYS_BEFORE_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_BEFORE_MONTH[month - 1] + day; if (isLeapYear() && month > 2) totalDays++; } int Date::getMaxDay()const { if (isLeapYear() && month == 2) { return 29; } else { return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1]; } } void Date::show() const { cout << getYear() << '-' << getMonth() << '-' << getDay(); }date.cpp
1 #ifndef _ACCUMULATOR_H_ 2 #define _ACCUMULATOR_H_ 3 #include "date.h" 4 class Accumulator { 5 private: 6 Date lastDate; 7 double value; 8 double sum; 9 public: 10 Accumulator(const Date& date, double value):lastDate(date),value(value),sum(0){ } 11 double getSum(const Date& date) const { 12 return sum + value * date.distance(lastDate); 13 } 14 void change(const Date& date, double value) { 15 sum = getSum(date); 16 lastDate = date; 17 this->value = value; 18 } 19 void reset(const Date& date, double value) { 20 lastDate = date; 21 this->value = value; 22 sum = 0; 23 } 24 }; 25 #endifaccumulator.h
1 #ifndef _ACCOUNT_H_ 2 #define _ACCOUNT_H_ 3 #include "date.h" 4 #include "accumulator.h" 5 #include <string> 6 class Account { 7 private: 8 std::string id; 9 double balance; 10 static double total; 11 protected: 12 Account(const Date& date, const std::string& id); 13 void error(const std::string& msg) const; 14 void record(const Date& data, double amount,const std::string& desc); 15 public: 16 const std::string& getId() const { return id; } 17 double getBalance() const { return balance; } 18 static double getTotal() { return total; } 19 void show() const; 20 }; 21 class SavingsAccount : public Account { 22 private: 23 Accumulator acc; 24 double rate; 25 public: 26 SavingsAccount(const Date& date, const std::string& id, double rate); 27 double getRate() const { return rate; } 28 void deposit(const Date& date, double amount, const std::string& desc); 29 void withdraw(const Date& date, double amount, const std::string& desc); 30 void settle(const Date& date); 31 }; 32 class CreditAccount : public Account { 33 private: 34 Accumulator acc; 35 double credit; 36 double rate; 37 double fee; 38 double getDebt()const { 39 double balance = getBalance(); 40 return (balance < 0 ? balance : 0); 41 } 42 public: 43 CreditAccount(const Date& date, const std::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 { return credit; } 48 void deposit(const Date& date, double amount, const std::string& desc); 49 void withdraw(const Date& date, double amount, const std::string& desc); 50 void settle(const Date& date); 51 void show() const; 52 }; 53 #endifacount.h
1 #include "account.h" 2 #include <iostream> 3 #include <cmath> 4 using namespace std; 5 double Account::total = 0; 6 7 // Account类的实现 8 Account::Account(const Date& date, const string& id) : id(id), balance(0) { 9 date.show(); 10 cout << "\t#" << id << " created" << endl; 11 } 12 13 void Account::record(const Date& date, double amount, const string& desc) { 14 amount = floor(amount * 100 + 0.5) / 100; 15 balance += amount;total += amount; 16 date.show(); 17 cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl; 18 } 19 20 void Account::show() const { 21 cout << id << "\tBalance: " << balance; 22 } 23 24 void Account::error(const string& msg) const { 25 cout << "Error(#" << id << "): " << msg << endl; 26 } 27 28 // SavingsAccount类相关成员函数的实现 29 SavingsAccount::SavingsAccount(const Date& date, const string& id, double rate) : 30 Account(date, id), rate(rate), acc(date, 0) {} 31 32 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) { 33 record(date, amount, desc); 34 acc.change(date, getBalance()); 35 } 36 37 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) { 38 if (amount > getBalance()) { 39 error("not enough money"); 40 } 41 else { 42 record(date, -amount, desc); 43 acc.change(date, getBalance()); 44 } 45 } 46 47 void SavingsAccount::settle(const Date& date) { 48 double interest = acc.getSum(date) * rate/date.distance(Date(date.getYear()-1,1,1)); 49 if (interest != 0) 50 record(date, interest, "interest"); 51 acc.reset(date, getBalance()); 52 } 53 54 // CreditAccount类相关成员函数的实现 55 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee) : 56 Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {} 57 58 59 void CreditAccount::deposit(const Date& date, double amount, const string& desc) { 60 record(date, amount, desc); 61 acc.change(date, getDebt()); 62 }account.cpp
1 #include "account.h" 2 #include <iostream> 3 using namespace std; 4 5 int main() { 6 Date date(2008, 11, 1); 7 8 SavingsAccount sa1(date, "S3755217", 0.015); 9 SavingsAccount sa2(date, "02342342", 0.015); 10 CreditAccount ca(date, "C5392394", 10000, 0.0005, 50); 11 12 sa1.deposit(Date(2008, 11, 5), 5000, "salary"); 13 ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell"); 14 sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323"); 15 16 ca.settle(Date(2008, 12, 1)); 17 18 ca.deposit(Date(2008, 12, 1), 2016, "repay the credit"); 19 sa1.deposit(Date(2008, 12, 5), 5500, "salary"); 20 21 sa1.settle(Date(2009, 1, 1)); 22 sa2.settle(Date(2009, 1, 1)); 23 ca.settle(Date(2009, 1, 1)); 24 25 cout << endl; 26 sa1.show(); cout << endl; 27 sa2.show(); cout << endl; 28 ca.show(); cout << endl; 29 cout << "Total: " << Account::getTotal() << endl; 30 return 0; 31 }7-10
标签:std,const,int,void,实验,date,include From: https://www.cnblogs.com/g055140/p/18566208