用C#生成一个“存款”类。包括:1.静态数据成员:当前存款额,对象个数(3个);(3个对象存款额分别为10000,20000,100000)常量成员:年利率--统一定义为3%。2.定义一个成员函数计算月利息:月利息=(存款*年利率)/12;并将这个月利率加入到当前存款额中;3.两种构造函数,即带参数和不带参数两种,增加并显示对象个数;4.一个析构函数,减少并显示对象个数;5.在主函数中实际化对象P1、P2和P3,并输出年利率对应的月利息及当前存款额;注意:要做界面设计,在界面的文本框中分别显示年利率、三个对象的存款额,并分别输出3个对象自存款36个月后的月利息和存款额。
时间: 2023-12-10 19:37:14 浏览: 95
以下是用C#实现的“存款”类:
```csharp
using System;
class SavingAccount
{
private static double currentBalance;
private static int numberOfAccounts = 0;
private const double annualInterestRate = 0.03;
private double balance;
public SavingAccount()
{
numberOfAccounts++;
balance = 0;
}
public SavingAccount(double initialBalance)
{
numberOfAccounts++;
balance = initialBalance;
currentBalance += balance;
}
~SavingAccount()
{
numberOfAccounts--;
}
public double CalculateMonthlyInterest()
{
double monthlyInterest = balance * annualInterestRate / 12;
balance += monthlyInterest;
currentBalance += monthlyInterest;
return monthlyInterest;
}
public static double GetCurrentBalance()
{
return currentBalance;
}
public static int GetNumberOfAccounts()
{
return numberOfAccounts;
}
}
```
在主函数中,我们可以实例化三个对象并输出它们的月利息和存款额:
```csharp
using System;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
SavingAccount account1 = new SavingAccount(10000);
SavingAccount account2 = new SavingAccount(20000);
SavingAccount account3 = new SavingAccount(100000);
double monthlyInterest1 = account1.CalculateMonthlyInterest();
double monthlyInterest2 = account2.CalculateMonthlyInterest();
double monthlyInterest3 = account3.CalculateMonthlyInterest();
double currentBalance = SavingAccount.GetCurrentBalance();
MessageBox.Show("年利率为3%,三个账户的存款额分别为:\n\n账户1:" + account1.GetBalance().ToString("C2") + "\n账户2:" + account2.GetBalance().ToString("C2") + "\n账户3:" + account3.GetBalance().ToString("C2") + "\n\n3个账户36个月后的月利息分别为:\n\n账户1:" + monthlyInterest1.ToString("C2") + "\n账户2:" + monthlyInterest2.ToString("C2") + "\n账户3:" + monthlyInterest3.ToString("C2") + "\n\n当前总存款额为:" + currentBalance.ToString("C2"));
Application.Run();
}
}
```
在界面上,我们可以添加一个文本框用于显示当前年利率和三个账户的存款额,以及一个按钮用于计算并输出月利息和当前总存款额。点击按钮后,程序会在界面上输出相关信息。
阅读全文