我正在计算每月付款,并接受多种输入(现金,贷款,贷款期限,利率),然后使用GetPayment()
计算每月付款。我需要使用2个不同的类,一个是程序,另一个是PaymentCalculator()
。
namespace ConsoleApp59
{
class Program
{
static void Main(string[] args)
{
PaymentCalculator calc1 = new PaymentCalculator();
calc1.SetCash(GetInput("cash flow: "));
calc1.SetLoan(GetInput("loan amount: "));
calc1.SetPeriod(GetInput("loan period (in months): "));
calc1.SetRate(GetInput("interest rate (ex. 10, 20): "));
calc1.GetPayment();
calc1.DisplayPayment();
ReadKey();
}
static double GetInput(string input)
{
Write("Please enter " + input);
double final = double.Parse(ReadLine());
return final;
}
}
public class PaymentCalculator
{
double cash, loan, period, rate, payment;
public PaymentCalculator()
{
cash = 0;
loan = 0;
period = 0;
rate = 0;
payment = 0;
}
public void SetCash(double input)
{
cash = input;
}
public void SetLoan(double input)
{
loan = input;
}
public void SetPeriod(double input)
{
period = input;
}
public void SetRate(double input)
{
rate = input;
}
public void GetPayment()
{
double firstCalculation = (loan * rate / 100);
double secondCalculation = (1 - 1 / Math.Pow(1 + rate / 100, period));
double payment = firstCalculation / secondCalculation;
}
public void DisplayPayment()
{
WriteLine("\t ----- Payment Calculator -----");
WriteLine("Monthly Payment: {0:F2}", payment);
}
}
}
我遇到的问题是,当我运行程序时,输出总是这样:
每月付款:0:00
不应该这样说,而是0.00
以外的任何其他号。我不知道为什么会这样,因为我在代码中找不到任何错误。
请有人告诉我为什么会这样,如何解决它,这样我才能得到实际数字作为答案。
答案 0 :(得分:4)
问题出在您的GetPayment方法中。
public void GetPayment()
{
double firstCalculation = (loan * rate / 100);
double secondCalculation = (1 - 1 / Math.Pow(1 + rate / 100, period));
double payment = firstCalculation / secondCalculation; // <-- right here.
}
您要声明一个名为Payment的新局部变量,该局部变量遮盖了DisplayPayment
方法中使用的类字段。由于从未更新过,因此class字段保留为初始值0,这是最终显示的值。
相反,将计算出的值分配给class字段。
payment = firstCalculation / secondCalculation;