實驗任務二:
#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; }
#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(); }
問題一:成績儲存在vector類中;透過vector中的介面來訪問;vector的push_back()介面
問題二:求平均數,1.0是將資料轉換成double型別,防止整數除法時丟失資料
問題三:沒有對輸入成績進行合法性檢查
實驗任務三:
#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; }
#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(); }
問題一:儲存在派生類定義的vector容器中;透過vector介面訪問;
問題二:類可以多種設計,可以繼承,使用基類元素,也可以自行封裝
實驗任務四:
#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(); }
#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(); }
問題一:讀取緩衝區中的換行符,使下一次字元可以正常輸入
問題二:多次輸入,並且在輸入n後去掉緩衝區中的換行符,以至於正常輸入
實驗任務五:
#include "C:\Users\29114\source\repos\MAJORCPP\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(); }
#include <iostream> #include <string> using namespace std; template<typename T> class GameResourceManager { private: T resource; public: GameResourceManager(T a); T get(); void update(T a); }; template<typename T> GameResourceManager<T>::GameResourceManager(T a) :resource{ a } {} template<typename T> T GameResourceManager<T>::get() { return resource; } template<typename T> void GameResourceManager<T>::update(T a) { resource = resource + a < 0 ? 0 : resource + a; }
實驗任務6
#include <iostream> #include <string> #include<iomanip> using namespace std; class info { private: string nickname; string contact; string city; int n; public: info(string name, string con, string city, int n); info() {}; void display(); }; info::info(string name, string con, string city, int n) :nickname{ name }, contact{ con }, city{ city }, n{ n } {} void info::display() { cout << "---------------------------------------------------" << endl; cout << left << setw(15) << "暱稱:" << left << setw(15) <<nickname<< endl; cout << left << setw(15) << "聯絡方式:" << left << setw(15) << contact << endl; cout << left << setw(15) << "所在城市:" << left << setw(15) << city << endl; cout << left << setw(15) << "預定人數:" << left << setw(15) << n << endl; }
#include<iostream> #include"c:/Users/29114/source/repos/MAJORCPP/info.hpp" using namespace std; #include<iomanip> #include<vector> #include<limits> int main() { const int capacity = 100; cout << "錄入使用者資訊:" << endl; cout << left << setw(15) << "暱稱" << left << setw(20) << "聯絡方式" << left << setw(15) << "所在城市" << left << setw(15) << "預定參加人數" << endl; vector<info> audience_list; string nickname, city, contact; int n; int now_cap = 0; while (true) { if (!(cin >> nickname >> contact >> city >> n)) break; if (now_cap + n > capacity) { cout << "對不起,只剩80個位置。" << endl; cout << "1.輸入u,更新預約資訊" << endl << "2.輸入q,退出預定" << endl << "你的選擇:" << endl; string a; cin >> a; if (a == "u") { cout << "請重新輸入預約資訊:" << endl; cin >> nickname >> contact >> city >> n; audience_list.push_back(info(nickname, contact, city, n)); } else if (a == "q") break; } else { now_cap += n; audience_list.push_back(info(nickname, contact, city, n)); } } cout << "截至目前,一共有" << now_cap << "位聽眾預約。預約聽眾資訊如下:" << endl; for (info& i : audience_list) i.display(); }
實驗任務七:
#ifndef __DATE_H__ #define __DATE_H__ 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; } }; #endif //__DATE_H__
#include "date.h" #include <iostream> #include <cstdlib> using namespace std; namespace { 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(); }
#pragma once #ifndef ACCUMULATOR_H #define ACCUMULATOR_H #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 = value; sum = 0; } }; #endif // ACCUMULATOR_H
#pragma once #ifndef ACCOUNT_H #define ACCOUNT_H #include "date.h" #include "accumulator.h" #include <string> class Account { private: std::string id; double balance; static double total; protected: Account(const Date& date, const std::string& id); void record(const Date& date, double amount, const std::string& desc); void error(const std::string& msg) const; public: const std::string& getId() const; double getBalance() const; static double getTotal(); void show() const; }; class SavingsAccount : public Account { private: Accumulator acc; double rate; public: SavingsAccount(const Date& date, const std::string& id, double rate); double getRate() const; void deposit(const Date& date, double amount, const std::string& desc); void withdraw(const Date& date, double amount, const std::string& desc); void settle(const Date& date); }; class CreditAccount : public Account { private: Accumulator acc; double credit; double rate; double fee; double getDebt() const; public: CreditAccount(const Date& date, const std::string& id, double credit, double rate, double fee); double getCredit() const; double getRate() const; double getAvailableCredit() const; void deposit(const Date& date, double amount, const std::string& desc); void withdraw(const Date& date, double amount, const std::string& desc); void settle(const Date& date); void show() const; }; #endif // ACCOUNT_H
#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 enough 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; }