C# 初学者,尝试创建一个程序,用户可以在其中输入金额、年份和费率,然后计算总金额。费率除以 100 得到小数值,年份乘以 12 得到月费率。
代码如下:
class Program
{
static void Main(string[] args)
{
CompoundClass program = new CompoundClass();
Console.Write("Please enter the initial balance for your account: ");
double balance = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the annual interest rate: ");
double interestRate = Convert.ToDouble(Console.ReadLine());
program.Rate(interestRate);
Console.Write("How many years will you acrue interest? ");
double anualAmount = Convert.ToDouble(Console.ReadLine());
program.Years(anualAmount);
Console.WriteLine($"Your balance after {anualAmount} years is {totalAmount:C}\n");
Console.ReadLine();
}
}
class CompoundClass
{
public double rate;
public double yearlyRate;
public double balance;
public void Rate(double interestRate)
{
if (interestRate > 0)
{
rate = interestRate / 100;
}
}
public void Years(double anualAmount)
{
if (anualAmount > 0)
{
yearlyRate = anualAmount * 12;
}
}
public void addMethod(double totalAmount)
{
for (int i = 1; i < yearlyRate + 1; i++)
{
totalAmount = balance * Math.Pow(1 + rate / yearlyRate, yearlyRate * i);
}
}
}
我不断收到错误:
CS0103The name 'totalAmount' does not exist in the current context.
我不知道是否有任何信息被正确提取和存储/计算。
您遇到该错误是因为“totalAmount”变量只能在 CompoundClass 中访问。这是因为它是使用默认访问修饰符 private 创建的。您为 CompoundClass 创建了一个对象
CompoundClass program = new CompoundClass();
您已经访问了使用该对象的方法。关于 annualAmount 或 interestRate 的问题,您没有从 CompoundClass 访问变量,您只是从 Program 类传递了它们。但是,您仍然可以通过 program.rate 等对象访问 rate、yearlyRate 和 balance。这是因为您已将它们声明为公开的。
public double rate;
public double yearlyRate;
public double balance;
如果您也想访问 totalAmount,请将其声明为公开。
program.addMethod(balance);
Console.WriteLine($"Your balance after {anualAmount} years is {program.totalAmount:C}\n");
我是一名优秀的程序员,十分优秀!