我有一个作业问题需要一些验证。我得到了问题第一部分的正确答案。然而,问题的第二部分效果不太好。我不确定是我的计算错误还是测试数据有误。 (今年已经发生过几次了).
我们应该设计一个控制台应用程序来解决还清贷款需要多少个月的问题。
我不能使用任何我还没学过的代码;只是基本代码。 (没有循环、数组等)
公式为: N = -(1/30) * ln(1+b/p(1-(1+i)^30)) / ln(1+i)
n = 月
ln = 对数函数
b = 信用卡余额
p=每月付款
i=日利率(年利率/365)
问题1的测试数据:
信用卡余额:$5000
每月付款:$200
年利率:0.28
我的答案:38个月
问题2的测试数据:
信用卡余额:$7500
每月付款:125 美元
年利率:0.22
无法得到答案
我的解决方案:
static void Main(string[] args)
{
decimal creditcardbalance, monthlypayment;
double calculation, months, annualpercentrate;
Console.WriteLine("Enter the credit card balance in dollars and cents: ");
creditcardbalance = decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter the monthly payment amount in dollars and cents: ");
monthlypayment = decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter the annual rate percentage as a decimal: ");
annualpercentrate = double.Parse(Console.ReadLine());
calculation = (Math.Log((1 + (double)(creditcardbalance / monthlypayment) * (1 - (Math.Pow(1 + (annualpercentrate / 365), 30)))))) / (Math.Log((1 + (annualpercentrate / 365))));
months = (-0.033333333333333333) * calculation;
Console.WriteLine("\nIt will take {0:F0} months to pay off the loan.", months);
Console.WriteLine("Goodbye!");
Console.ReadLine();
}
你的问题是你试图取负数的对数。这就是为什么你得到“NaN”(不是数字)的结果。
但是为什么第二个例子中 1+b/p(1-(1+i)^30) 是负数呢? 嗯,这很简单。因为你每个月的利息比你每月的还款额还多!
7500 美元 * 0.22 / 12 = 137.5 美元
由于您每月的还款额仅为 125 美元,因此您将需要无数个月(说:永远不会)来偿还债务。
NaN 是编程语言表示不可计算结果的方式。
所以,你没有编程问题,你有债务问题。也许这是 money.stackexchange.com ;-)
的问题更准确的计算应基于每日利率乘以上次*与当前付款之间的天数;像这样的东西:
var interest_amount = (annual_interest_rate / 365_or_366_if_IsLeapYear) * daydiff(current_payment_date, last_payment_date);
*对于第一次付款,“最后”日期应为信用证开立的日期。