码迷,mamicode.com
首页 > 编程语言 > 详细

2020春c++计算存款利息

时间:2020-04-11 18:30:53      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:gac   double   balance   flag   space   save   pre   数据   保存   

创建一个SavingAccount类. 使用一个static数据成员annualInterestRate保存每个存款者的年利率。类的每个对象都包含一个private数据成员savingBalance,用以指示存款者目前的存款金额。该类提供成员函数calculateMonthlyInterest,它将余额乘以annualInterestRate再除以12来计算月利息,这个利息应该加到savingBalance中。该类还提供一个static成员函数modifyInterestRate,它将static的annualInterestRate设置为一个新值。在主函数中,实例化SavingAccount类的两个对象saver1和saver2,余额分别是2000和3000,将annualInterestRate设置为3%,然后计算月利率并打印每个存款者的新余额,接着再将annualInterestRate设置为4%,计算下一个月的利息并打印每个存款者的新余额。
#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
#include<iomanip>
using namespace std;

class SavingsAccount
{
public:
SavingsAccount(double save):savingBalance(save){}
double calculateMonthlyInterest();
void printBalance();
static double modifyInterestRate(double rate);

private:
static double annualInterestRate;
double savingBalance;
};
double SavingsAccount::annualInterestRate=0;
double SavingsAccount::modifyInterestRate(double rate){
annualInterestRate=rate;
return annualInterestRate;
}
double SavingsAccount::calculateMonthlyInterest(){
savingBalance+=savingBalance*annualInterestRate/12;
return savingBalance;
}
void SavingsAccount::printBalance(){
cout<<"$"<<setiosflags(ios::fixed)<<setprecision(2)<<savingBalance<<endl;
}

 

int main(){
SavingsAccount saver1(2000.0);
SavingsAccount saver2(3000.0);
SavingsAccount::modifyInterestRate(0.03);

cout<<"Initial balances:\nSaver 1:";
saver1.printBalance();
cout<<"Saver 2:";
saver2.printBalance();

saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();

cout<<"\n \nBalances after 1 month‘s interest applied at .03 \n"<<"Saver 1:";
saver1.printBalance();
cout<<"Saver 2:";
saver2.printBalance();

SavingsAccount::modifyInterestRate(0.04);
//change interest rate
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();

cout<<"\n\nBalances after 1 month‘s interest applied at: .04\n"<<"Saver 1:";
saver1.printBalance();
cout<<"Saver 2:";
saver2.printBalance();
cout<<endl;
getchar();
return 0;
}

2020春c++计算存款利息

标签:gac   double   balance   flag   space   save   pre   数据   保存   

原文地址:https://www.cnblogs.com/zhaoyiyao/p/12681324.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!