实现给出初始余额,返回利率及存期,计算出到期时的余额。要求要将余额记录为两个int值,一个用于美元,一个用于美分,并将利率作为小数而非百分数来存储。
其具体实现代码如下:
#include<iostream>
#include<cmath>
using namespace std;
class CDAccount
{
public:
CDAccount();
CDAccount(double dparts,double cparts,double rate, int term1);
double getBanlance();
double getRate();
int getTerm();
void update();
void output(ostream &outs);
private:
double interestRate;
int term;
double dollarParts;
double centParts;
double fraction(double percent);
};
CDAccount::CDAccount()
{
dollarParts = 0;
centParts = 0;
interestRate = 0;
term = 0;
}
CDAccount::CDAccount(double dparts,double cparts,double rate, int term1)
{
dollarParts = dparts;
centParts = cparts;
interestRate = fraction(rate);
term = term1;
}
double CDAccount::getRate()
{
return interestRate;
}
int CDAccount::getTerm()
{
return term;
}
double CDAccount::fraction(double percent)
{
return (percent/100.0);
}
void CDAccount::update()
{
double balance = getBanlance();
balance = balance+balance*interestRate*term;
dollarParts = static_cast<int>(floor(balance));
centParts = static_cast<int>(floor(balance - dollarParts)*100);
cout<<"到期时余额的整数美元部分为:"<<dollarParts<<endl;
cout<<"到期时余额的整数美分部分为:"<<centParts<<endl;
}
double CDAccount::getBanlance()
{
return (dollarParts + centParts*0.01);
}
void CDAccount::output(ostream& outs)
{
outs.setf(ios::fixed);
outs.setf(ios::showpoint);
outs.precision(2);
outs<<"账户余额为:"<<getBanlance()<<endl;
outs<<"账户利率为:"<<getRate()<<endl;
}
int main()
{
CDAccount account1(10,0,10,1),account2;
account1.update();
cout<<"account1 initialized as follows: \n" ;
account1.output(cout);
cout<<"account2 initialized as follows: \n" ;
account2.output(cout);
return 0;
}