c++程序设计基础实验4

任务2:


源代码:

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>());//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 <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>());//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; 
} 

运行结果截图:

 问题1:

该派生类为vector<int>容器类的派生类,因此录入的成绩都储存在派生类的private数据中,虽然在代码中没有体现,但是在c++的标准库中含有vector容器类的声明和定义。

上述的函数都是通过vector容器类的public函数访问成绩的数据的,input()函数是通过vector容器类中的push—back()函数接口来输入数据并储存在派生类中的,push-back()集团口可以实现在vector<int>动态数组后面增加录入元素。

问题2:
分母的作用是计算各个分数区间的人数占总人数的小数比值,通过乘以1.0,可以将分子上的数值转换为double型,在计算后可以实现产生小数,方便后续计算百分比时的保留两位小数输出。如果不乘以1.0,编译器就会调用整型数的整除,这样几个百分比都会变成0。

问题3:
该项目虽然可以宏观计算成绩的数据,但是对于每一个学生的数据统计不完善,可以在后续的派生类中加入学号,姓名,排名等private数据成员,使每一个学生的成绩更加直观。可以在public接口加入查询功能,通过学号或者姓名来查询成绩。或者通过成绩来输出该成绩的学生的个人信息,更符合实际的应用场景。

 

任务3:

源代码:

 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();
}

运行结果截图:

 问题1:

该段代码储存在vector动态数组中,上述函数都是通过vector<int>grade动态数组中的public接口来实现对成绩的访问和处理的。

该段代码和任务2的区别主要是,任务2的代码更多的使用了this指针对vector容器类的begin(),end()接口去实现数据的数额u输出和计算,而任务3则直接对vector容器类的接口进行了调用,写法更加地直接。

问题二:

同一个项目在处理问题和架构结构时,可以使用不同的方法,可以运用指针来访问和处理数据,也可以利用标准库中的函数和接口来处理,虽然都能实现相同的结果,但是我们在处理数据时如果充分利用标注库的接口和函数,能够简化项目的代码的结构复杂度,也能够提高代码的可读性,更能方便后续的修改和拓展结构。相反,如果自己创建和声明新的结构时,虽然功能都可以实现,但是在后续的改进和更新中会不可避免得导致结构的改变,还有可能导致数据的泄露,结构的不安全性,因此要充分理解并熟练运用标准库的内容和接口,如STL容器的各种处理容器数据的函数接口,它们都是安全且稳定的接口;

 

任务4:

源代码:

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();
}

运行结果截图:
注释:将定义间隔符换为了','

 问题:

在将该行代码去除后,测试2将无法读取第一个元素,这是因为cin输入流的缓冲区还保存了第一次输入的空格,而缓冲区没有被及时清除导致了第二次输入时默认将空白读取为了s1,因此s1无法被读取,我们要输入的s1因为原本的位置被读取,所以被编译器赋值到了s2。因此,推测该行代码的作用是清除缓冲区的内存。

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();
}

运行结果截图:

 task-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();
}

运行结果截图:

 问题:

 该段代码的作用是清除输入缓存区的缓存,避免缓存区存取的字符串被错误读取。

 

任务5:

源代码:
grm.hpp:

#ifndef GRM_HPP
#define GRM_HPP

template <typename T>
class GameResourceManager {
private:
    T resource; // 资源的当前值

public:
    // 构造函数,初始化资源的初始值
    explicit GameResourceManager(T initial_value) : resource(initial_value) {}

    // 获取当前资源值
    T get() const {
        return resource;
    }

    // 更新资源值
    void update(T delta) {
        resource += delta;
        if (resource < 0) {
            resource = 0; // 防止资源值低于0
        }
    }
};

#endif // GRM_HPP

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();
}

运行结果截图:

 

任务6:

源代码:
info.hpp:

#ifndef INFO_HPP
#define INFO_HPP

#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;

class Info {
private:
    string nickname;   // 昵称
    string contact;    // 联系方式 (email 或手机号)
    string city;       // 所在城市
    int num_people;    // 预定人数

public:
    // 带参数的构造函数
    Info(const string& nickname, const string& contact, const string& city, int num_people)
        : nickname(nickname), contact(contact), city(city), num_people(num_people) {
    }

    // 显示信息
    void display() const {
        cout << "昵称: " << nickname
            << ", 联系方式: " << contact
            << ", 所在城市: " << city
            << ", 预定参加人数: " << num_people << endl;
    }

    // 获取预定人数
    int get_num_people() const {
        return num_people;
    }

    // 更新预定人数
    void update_num_people(int new_num_people) {
        num_people = new_num_people;
    }
};

#endif // INFO_HPP

task6.cpp:

#include "info.hpp"
#include <vector>
#include <iostream>
using std::vector;
using std::cin;
using std::cout;
using std::endl;

int main() {
    const int capacity = 100;            // livehouse最多容纳人数
    int remaining_capacity = capacity;  // 剩余容量
    vector<Info> audience_lst;          // 存放预约用户的信息

    while (remaining_capacity > 0) {
        cout << "请输入预约信息 (昵称、联系方式、所在城市、预定人数):" << endl;

        string nickname, contact, city;
        int num_people;

        // 从键盘输入信息
        cin >> nickname >> contact >> city >> num_people;

        // 检查是否输入超出剩余容量
        if (num_people > remaining_capacity) {
            cout << "剩余容量不足,最多还可预定: " << remaining_capacity << " 人。" << endl;
            cout << "请输入 'q' 退出预定,或 'u' 更新预定人数:" << endl;

            char choice;
            cin >> choice;

            if (choice == 'q') {
                cout << "退出预定。" << endl;
                break;
            }
            else if (choice == 'u') {
                cout << "请输入新的预定人数:" << endl;
                cin >> num_people;

                if (num_people > remaining_capacity) {
                    cout << "更新后的预定人数仍超过剩余容量。预定失败。" << endl;
                    continue;
                }
            }
            else {
                cout << "无效输入,请重新预约。" << endl;
                continue;
            }
        }

        // 更新剩余容量并保存信息
        remaining_capacity -= num_people;
        audience_lst.emplace_back(nickname, contact, city, num_people);
        cout << "预约成功!当前剩余容量: " << remaining_capacity << endl;

        // 停止条件
        cout << "是否继续输入?(输入 'n' 停止,其他任意键继续):" << endl;
        char stop;
        cin >> stop;
        if (stop == 'n') {
            break;
        }
    }
    int u = capacity - remaining_capacity;
    // 打印所有预约信息
    cout << "截至目前,一共有" << u<< "位观众参与预约。预约听众信息如下:"<< endl;
    for (const auto& audience : audience_lst) {
        audience.display();
    }

    return 0;
}

运行结果截图:

 任务7:

date.h:

1 #pragma once
 2 class Date{
 3     private:
 4         int year;
 5         int month;
 6         int day;
 7         int totalDays;
 8     public:
 9         Date(int year,int month,int day);
10         int getYear()const {return year;}
11         int getMonth()const{return month;}
12         int getDay()const{return day;}
13         int getMaxDay()const;
14         bool isLeapYear()const{
15             return year%4==0&&year%100!=0||year%400==0;
16         }
17         void show()const;
18         int distance(const Date&date)const{
19             return totalDays-date.totalDays;
20         }
21 };


date.cpp:

1 #include"date.h"
 2 #include<iostream>
 3 #include<cstdlib>
 4 using namespace std;
 5 namespace{
 6     const int DAYS_BEFORE_MONTH[]={0,31,59,90,120,151,181,212,243,273,304,334,365};
 7 }
 8 Date::Date(int year,int month,int day):year(year),month(month),day(day){
 9     if(day<=0||day>getMaxDay()){
10         cout<<"Invalid date: ";
11         show();
12         cout<<endl;
13         exit(1);
14     }
15     int years=year-1;
16     totalDays=years*365+years/4-years/100+years/400+DAYS_BEFORE_MONTH[month-1]+day;
17     if(isLeapYear()&&month>2)totalDays++;
18 }
19 int Date::getMaxDay()const{
20     if(isLeapYear()&&month==2)
21         return 29;
22     else
23         return DAYS_BEFORE_MONTH[month]-DAYS_BEFORE_MONTH[month-1];
24 }
25 void Date::show()const{
26     cout<<getYear()<<"-"<<getMonth()<<"-"<<getDay();
27 }


accumulator.h:

1 #pragma once
 2 #include "date.h"
 3 class Accumulator {
 4 private:
 5     Date lastDate;
 6     double value;
 7     double sum;
 8 public:
 9     Accumulator(const Date&date,double value):lastDate(date),value(value),sum{0}{}
10     double getSum(const Date& date) const {
11         return sum + value * date.distance(lastDate);
12     }
13     void change(const Date& date, double value) {
14         sum = getSum(date);
15         lastDate = date;
16         this->value = value;
17     }
18     void reset(const Date& date, double value) {
19         lastDate = date;
20         this->value;
21         sum = 0;
22     }
23 };


account.h:

1 #pragma once
 2 #include"date.h"
 3 #include"accumulator.h"
 4 #include<string>
 5 using namespace std;
 6 class Account {
 7 private:
 8     string id;
 9     double balance;
10     static double total;
11 protected:
12     Account(const Date& date, const string &id);
13     void record(const Date& date, double amount, const string& desc);
14     void error(const string& msg) const;
15 public:const string& getId() { return id; }
16       double getBalance()const { return balance; }
17       static double getTotal() { return total; }
18       void show()const;
19 };
20 class SavingsAccount:public Account {
21 private:
22     Accumulator acc;
23     double rate;
24 public:
25     SavingsAccount(const Date& date, const string& id, double rate);
26     double getRate() const { return  rate; }
27     void deposit(const Date& date, double amount, const string& desc);
28     void withdraw(const Date& date, double amount, const string& desc);
29     void settle(const Date& date);
30 };
31 class CreditAccount :public Account {
32 private:
33     Accumulator acc;
34     double credit;
35     double rate;
36     double fee;
37     double getDebt()const {
38         double balance = getBalance();
39         return(balance < 0 ? balance : 0);
40     }
41 public:CreditAccount(const Date& date, const string& id, double credit, double rate, double fee);
42       double getCredit()const { return credit; }
43       double getRate()const { return rate; }
44       double getFee() const { return fee; }
45       double getAvailableCredit()const {
46           if (getBalance() < 0)return credit + getBalance();
47           else return credit;
48       }
49       void deposit(const Date& date, double amount, const string& desc);
50       void withdraw(const Date& date, double amount, const string& desc);
51       void settle(const Date& date);
52       void show()const;
53 };


account.cpp:

1 #include"account.h"
 2 #include<cmath>
 3 #include<iostream>
 4 using namespace std;
 5 double Account::total=0;
 6 Account::Account(const Date &date,const string &id)
 7     :id(id),balance(0){
 8         date.show();cout<<"\t#"<<id<<"created"<<endl;
 9     }
10 void Account::record(const Date &date,double amount,const string &desc){
11     amount=floor(amount*100+0.5)/100;
12     balance+=amount;total+=amount;
13     date.show();
14     cout<<"\t#"<<id<<"\t"<<amount<<"\t"<<balance<<"\t"<<desc<<endl;
15 }
16 void Account::show()const{cout<<id<<"\tBalance:"<<balance;}
17 void Account::error(const string &msg)const{
18     cout<<"Error(#"<<id<<"):"<<msg<<endl;
19 }
20 SavingsAccount::SavingsAccount(const Date&date,const string &id,double rate):Account(date,id),rate(rate),acc(date,0){}
21 void SavingsAccount::deposit(const Date& date, double amount, const string& desc) {
22     record(date, amount, desc);
23     acc.change(date, getBalance());
24 }
25 void SavingsAccount::withdraw(const Date& date, double amount, const string& desc) {
26     if (amount > getBalance()) {
27         error("not enough money");
28     }
29     else {
30         record(date, -amount, desc);
31         acc.change(date, getBalance());
32     }
33 }
34 void SavingsAccount::settle(const Date& date) {
35     double interest = acc.getSum(date) * rate/date.distance(Date(date.getYear()-1,1,1));
36     if (interest != 0)record(date, interest, "interest");
37     acc.reset(date, getBalance());
38 }
39 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){}
40 void CreditAccount::deposit(const Date& date, double amount, const string& desc) {
41     record(date, amount, desc);
42     acc.change(date, getDebt());
43 }
44 void CreditAccount::withdraw(const Date& date, double amount, const string& desc) {
45     if (amount - getBalance() > credit) {
46         error("not enouogh credit");
47     }
48     else {
49         record(date, -amount, desc);
50         acc.change(date, getDebt());
51     }
52 }
53 void CreditAccount::settle(const Date& date) {
54     double interest = acc.getSum(date) * rate;
55     if (interest != 0) record(date, interest, "interest");
56     if (date.getMonth() == 1)record(date, -fee, "annual fee");
57     acc.reset(date, getDebt());
58 }
59 void CreditAccount::show()const {
60     Account::show();
61     cout << "\tAvailable credit:" << getAvailableCredit();
62 }

7_10.cpp:

1 #include "account.h"
 2 #include<iostream>
 3 using namespace std;
 4 int main() {
 5     Date date(2008, 11, 1);
 6     SavingsAccount sa1(date, "S3755217", 0.015);
 7     SavingsAccount sa2(date, "02342342", 0.015);
 8     CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);
 9     sa1.deposit(Date(2008, 11, 5), 5000, "Salary");
10     ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell");
11     sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
12     ca.settle(Date(2008, 12, 1));
13     ca.deposit(Date(2008, 12,1), 2016, "repay the credit");
14     sa1.deposit(Date(2008, 12, 5), 5500, "salary");
15     sa1.settle(Date(2009, 1, 1));
16     sa2.settle(Date(2009, 1, 1));
17     ca.settle(Date(2009, 1, 1));
18     cout << endl;
19     sa1.show(); cout << endl;
20     sa2.show(); cout << endl;
21     ca.show(); cout << endl;
22     cout << "Total: " << Account::getTotal() << endl;
23     return 0;
24 }

运行结果截图:

 

posted @ 2024-11-24 16:17  相梓文  阅读(4)  评论(0编辑  收藏  举报