定义SavingsAccount类,类中有如下成员:
1.静态变量annualInterestRate存储所有账户持有者的年利率。
2.类的每个对象包含一个专用实例变量savingBalance,表示该存款账户当前的金额。
3.定义CalculateMonthlyInterest方法,将annualInterestRate与savingBalance相乘后除以12得到月利息,这个月利息加进savingBalance中。
4.定义静态方法ModifyInterestRate,将savingBalance设置为新值。
测试SavingsAccount类,创建两个SavingsAccount的对象saver1和saver2,结余分别为2000.0美元和3000.0美元。将annualInterestRate设置为4%,然后计算月息,并将月息加入账户结余后,输出两个账户的新结余。然后将annualInterestRate设置为5%,再次输出新的结余。
实现代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { SavingsAccount saver1 = new SavingsAccount(); SavingsAccount saver2 = new SavingsAccount(); SavingsAccount.ModifyInterestRate(saver1, 2000); SavingsAccount.ModifyInterestRate(saver2, 3000); SavingsAccount.annualInterestRate = 0.04; saver1.CalculateMonthlyInterest(); saver2.CalculateMonthlyInterest(); saver1.show(); saver2.show(); SavingsAccount.annualInterestRate = 0.05; saver1.CalculateMonthlyInterest(); saver2.CalculateMonthlyInterest(); saver1.show(); saver2.show(); Console.ReadLine(); } } class SavingsAccount { private double savingBalance; static public double annualInterestRate; public void CalculateMonthlyInterest() { savingBalance += annualInterestRate * savingBalance / 12.0; } public static void ModifyInterestRate(SavingsAccount s, double arges) { s.savingBalance = arges; } public void show() { Console.WriteLine("帐户结余:{0}", savingBalance); } } } |
测试结果:
