活期储存账户,包括账户(id),余额(balance),年利率(rate)等信息,还包括账户信息显示(show),存款(deposit),取款(withdraw),结算利息(settle)等操作
设计一个类savingaccount,将id,balance,rate为数据成员,将show,deposit,withdraw,settle设为函数成员
无论存款,取款,还是结算利息,都需要修改余额并且输出,该操作由record来执行
关键点在于计算利息
余额不断变化,可以通过将余额加起来再除于天数,得一个日均余额再乘rate,方便计日期引入私有数据成员lastdate,accumulation,函数成员accumulate,lastdate记录余额变动的日期,accumulation记录用来存储上次计算利息以后直到最近一次余额变动时余额按日累加的值
accumulate来计算截至指定日期的账户余额按日累积值,当余额变动时,就可以将变动前余额与该余额所持天数相乘,累加到accumulation中,并且改变lastdate
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cmath>
using namespace std;
class SavingAccount {
private:
int id;
double balance;
double rate;
int LastDate;
double accumulation;//余额按日累加之和
void record(int date, double amount);
double accumulate(int date)const {
return accumulation + balance * (date - LastDate);
}
public:
SavingAccount(int date, int id, double rate);
int getid() { return id; }
double getBalance() { return balance; }
double getrate() { return rate; }
void depose(int date, double amount);
void withdraw(int date, double amount);
void settle(int date);
void show();
};
SavingAccount::SavingAccount(int date, int id, double rate) :id(id), balance(0),
rate(rate), LastDate(date), accumulation(0) {
cout << date << "\t#" << id << "is created" << endl;
}
void SavingAccount::record(int date, double amount) {
accumulation = accumulate(date);
LastDate = date;
amount = floor(amount*100 + 0.5) / 100;
balance += amount;
cout << date << "\t#" << id << "\t" << amount << "\t" << balance << endl;
}
void SavingAccount::depose(int date, double amount) {
record(date, amount);
}
void SavingAccount::withdraw(int date, double amount) {
if (amount > getBalance())
cout << "not enough mony" << endl;
else
record(date, -amount);
}
void SavingAccount::settle(int date) {
double interest = accumulate(date) * rate / 365;
if (interest != 0)
record(date, interest);
accumulation = 0;
}
void SavingAccount::show() {
cout << "#" << id << "\tBalance:" << balance;
}
int main() {
SavingAccount sa0(1, 21325302, 0.015);
SavingAccount sa1(1, 51325302, 0.015);
sa0.depose(5, 5000);
sa1.depose(25, 10000);
sa0.depose(45, 5500);
sa1.withdraw(60, 4000);
sa0.settle(90);
sa1.settle(90);
sa0.show();
sa1.show();
}