實驗四

练就有用發表於2024-11-25
實驗任務一
task1_1.cpp
 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 }

task1_2.cpp
 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 }

實驗任務二

GradeCalc.hpp

  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);//儲存各分數段人數
 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 }
task2.cpp
 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 #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 }
106 
107 
108 
109 #include "GradeCalc.hpp"
110 #include <iomanip>
111 
112 void test() {
113     int n;
114     cout << "輸入班級人數: ";
115     cin >> n;
116 
117     GradeCalc c1("OOP", n);
118 
119     cout << "錄入成績: " << endl;;
120     c1.input();
121     cout << "輸出成績: " << endl;
122     c1.output();
123 
124     cout << string(20, '*') + "課程成績資訊"  + string(20, '*') << endl;
125     c1.info();
126 }
127 
128 int main() {
129     test();
130 }

實驗任務四

task4_1.cpp
 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 }

忽略輸入流cin中從當前位置開始直到下一個換行符(包括換行符本身)的所有字元 避免前一次輸入的換行符或多餘字元影響到下一次輸入

task4_2.cpp
 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 }

 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 }

cin讀取時會跳過換行符,getline不會,但是getline會處理輸入最後的換行符確保不會被下一次讀到

實驗任務五

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

 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 }

實驗任務六

info.hpp

 1 #ifndef INFO_HPP
 2 #define INFO_HPP
 3 #include<iostream>
 4 #include <string>
 5 
 6 class Info {
 7 private:
 8     std::string nickname;
 9     std::string contact;
10     std::string city;
11     int n;
12 
13 public:
14     // 帶引數的建構函式,用於初始化預約資訊
15     Info(const std::string& _nickname, const std::string& _contact, const std::string& _city, int _n)
16         : nickname(_nickname), contact(_contact), city(_city), n(_n) {}
17 
18     // 顯示資訊(暱稱、聯絡方式、所在城市、預定參加人數)
19     void display() const {
20         std::cout << "暱稱: " << nickname << std::endl;
21         std::cout << "聯絡方式: " << contact << std::endl;
22         std::cout << "所在城市: " << city << std::endl;
23         std::cout << "預定參加人數: " << n << std::endl;
24     }
25 
26     // 獲取預定參加人數
27     int getN() const {
28         return n;
29     }
30 };
31 
32 #endif

6.cpp

 1 #include "info.hpp"
 2 #include <iostream>
 3 #include <vector>
 4 #include <string>
 5 #include <limits>
 6 
 7 int main() {
 8     // 定義一個const常量capacity用於存放livehouse最多能容納的聽眾人數
 9     const int capacity = 100;
10 
11     // 定義一個vector<Info>類物件audience_lst,用於存放線上預約登記的所有聽眾資訊
12     std::vector<Info> audience_lst;
13 
14     // 當前已預約的人數
15     int currentCapacity = 0;
16 
17     std::string nickname, contact, city;
18     int n;
19 
20     std::cout << "請輸入預約資訊(暱稱 聯絡方式 所在城市 預定參加人數,以空格分隔,輸入Ctrl+Z或達到場地容量時停止錄入):" << std::endl;
21 
22     while (true) {
23         if (!(std::cin >> nickname >> contact >> city >> n)) {
24             // 檢測到Ctrl+Z,結束輸入
25             if (std::cin.eof()) {
26                 break;
27             }
28             // 輸入錯誤,清除錯誤狀態並忽略當前行剩餘字元
29             std::cin.clear();
30             std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
31             continue;
32         }
33 
34         if (currentCapacity + n > capacity) {
35             std::cout << "預定參加人數超過livehouse場地剩餘容量,請輸入q退出預定,或輸入u更新預定資訊:";
36             std::string choice;
37             std::cin >> choice;
38 
39             if (choice == "q") {
40                 break;
41             }
42             else if (choice == "u") {
43                 std::cout << "請重新輸入預約資訊(暱稱 聯絡方式 所在城市 預定參加人數,以空格分隔):";
44                 continue;
45             }
46             else {
47                 std::cout << "無效選擇,請重新輸入。" << std::endl;
48                 continue;
49             }
50         }
51 
52         Info newInfo(nickname, contact, city, n);
53         audience_lst.push_back(newInfo);
54         currentCapacity += n;
55 
56         if (currentCapacity >= capacity) {
57             std::cout << "已達到場地最大容納人數,停止預約。" << std::endl;
58             break;
59         }
60     }
61 
62     // 列印輸出預約參加livehouse的聽眾資訊
63     std::cout << "預約參加livehouse的聽眾資訊如下:" << std::endl;
64     for (const auto& info : audience_lst) {
65         info.display();
66     }
67 
68     return 0;
69 }

實驗任務七

  1 #include "account.h"
  2 #include <cmath>
  3 #include <iostream>
  4 using namespace std;
  5 
  6 double Account::total = 0;
  7 
  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;
 16     total += amount;
 17     date.show();
 18     cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
 19 }
 20 
 21 void Account::show() const {
 22     cout << id << "\tBalance: " << balance;
 23 }
 24 
 25 void Account::error(const string& msg) const {
 26     cout << "Error(#" << id << "): " << msg << endl;
 27 }
 28 
 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     } else {
 41         record(date, -amount, desc);
 42         acc.change(date, getBalance());
 43     }
 44 }
 45 
 46 void SavingsAccount::settle(const Date& date) {
 47     double interest = acc.getSum(date) * rate / date.distance(Date(date.getYear() - 1, 1, 1));
 48     if (interest != 0) record(date, interest, "interest");
 49     acc.reset(date, getBalance());
 50 }
 51 
 52 CreditAccount::CreditAccount(const Date& date, const string& id, double credit, double rate, double fee)
 53     : Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {}
 54 
 55 void CreditAccount::deposit(const Date& date, double amount, const string& desc) {
 56     record(date, amount, desc);
 57     acc.change(date, getDebt());
 58 }
 59 
 60 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) {
 61     if (amount - getBalance() > credit) {
 62         error("not enough credit");
 63     } else {
 64         record(date, -amount, desc);
 65         acc.change(date, getDebt());
 66     }
 67 }
 68 
 69 void CreditAccount::settle(const Date& date) {
 70     double interest = acc.getSum(date) * rate;
 71     if (interest != 0) record(date, interest, "interest");
 72     if (date.getMonth() == 1) record(date, -fee, "annual fee");
 73     acc.reset(date, getDebt());
 74 }
 75 
 76 void CreditAccount::show() const {
 77     Account::show();
 78     cout << "\tAvailable credit: " << getAvailableCredit();
 79 }
 80 
 81 #pragma once
 82 #ifndef ACCOUNT_H
 83 #define ACCOUNT_H
 84 
 85 #include "date.h"
 86 #include "accumulator.h"
 87 #include <string>
 88 
 89 class Account {
 90 private:
 91     std::string id;
 92     double balance;
 93     static double total;
 94 
 95 protected:
 96     Account(const Date& date, const std::string& id);
 97     void record(const Date& date, double amount, const std::string& desc);
 98     void error(const std::string& msg) const;
 99 
100 public:
101     const std::string& getId() const { return id; }
102     double getBalance() const { return balance; }
103     static double getTotal() { return total; }
104 
105     void show() const;
106 };
107 
108 class SavingsAccount : public Account {
109 private:
110     Accumulator acc;
111     double rate;
112 
113 public:
114     SavingsAccount(const Date& date, const std::string& id, double rate);
115     double getRate() const { return rate; }
116 
117     void deposit(const Date& date, double amount, const std::string& desc);
118     void withdraw(const Date& date, double amount, const std::string& desc);
119     void settle(const Date& date);
120 };
121 
122 class CreditAccount : public Account {
123 private:
124     Accumulator acc;
125     double credit;
126     double rate;
127     double fee;
128 
129     double getDebt() const {
130         double balance = getBalance();
131         return (balance < 0 ? balance : 0);
132     }
133 
134 public:
135     CreditAccount(const Date& date, const std::string& id, double credit, double rate, double fee);
136     double getCredit() const { return credit; }
137     double getRate() const { return rate; }
138     double getAvailableCredit() const {
139         if (getBalance() < 0)
140             return credit + getBalance();
141         else
142             return credit;
143     }
144 
145     void deposit(const Date& date, double amount, const std::string& desc);
146     void withdraw(const Date& date, double amount, const std::string& desc);
147     void settle(const Date& date);
148     void show() const;
149 };
150 
151 #endif // ACCOUNT_H
152 
153 
154 #pragma once
155 #ifndef ACCUMULATOR_H
156 #define ACCUMULATOR_H
157 
158 #include "date.h"
159 
160 class Accumulator {
161 private:
162     Date lastDate;
163     double value;
164     double sum;
165 
166 public:
167     Accumulator(const Date& date, double value) : lastDate(date), value(value), sum{0} {}
168 
169     double getSum(const Date& date) const {
170         return sum + value * date.distance(lastDate);
171     }
172 
173     void change(const Date& date, double value) {
174         sum = getSum(date);
175         lastDate = date;
176         this->value = value;
177     }
178 
179     void reset(const Date& date, double value) {
180         lastDate = date;
181         this->value = value;
182         sum = 0;
183     }
184 };
185 
186 #endif // ACCUMULATOR_H
187 
188 
189 #include "date.h"
190 #include <iostream>
191 #include <cstdlib>
192 using namespace std;
193 
194 namespace {
195     const int DAYS_BEFORE_MONTH[] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 };
196 }
197 
198 Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
199     if (day <= 0 || day > getMaxDay()) {
200         cout << "Invalid date:";
201         show();
202         cout << endl;
203         exit(1);
204     }
205     int years = year - 1;
206     totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
207     if (isLeapYear() && month > 2) totalDays++;
208 }
209 
210 int Date::getMaxDay() const {
211     if (isLeapYear() && month == 2)
212         return 29;
213     else
214         return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
215 }
216 
217 void Date::show() const {
218     cout << getYear() << "-" << getMonth() << "-" << getDay();
219 }
220 
221 
222 #ifndef __DATE_H__
223 #define __DATE_H__
224 
225 class Date {
226 private:
227     int year;
228     int month;
229     int day;
230     int totalDays;
231 
232 public:
233     Date(int year, int month, int day);
234     int getYear() const { return year; }
235     int getMonth() const { return month; }
236     int getDay() const { return day; }
237     int getMaxDay() const;
238     bool isLeapYear() const {
239         return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
240     }
241     void show() const;
242     int distance(const Date& date) const {
243         return totalDays - date.totalDays;
244     }
245 };
246 
247 #endif // __DATE_H__

相關文章