控制台一直给我NAN
本文关键字:NAN 一直 控制台 | 更新日期: 2023-09-27 18:22:02
我正在编写一个简单的贷款偿还计算器。当我运行此代码时,无论我使用什么数字,控制台都会输出"Nan"。我不确定我的数学是不是错了,或者我是否滥用了";数学"作用
int choice=1;
Console.WriteLine("1. Find out how many months it will take to pay off the loan: ");
Console.WriteLine("2. Can I afford it? ");
Console.WriteLine("3. Exit ");
choice = int.Parse(System.Console.ReadLine());
if (choice == 1){
Console.WriteLine("Enter amount borrowed: ");
double borrowed = double.Parse(System.Console.ReadLine());
Console.WriteLine("Enter the interest rate: ");
double rate = double.Parse(System.Console.ReadLine());
Console.WriteLine("Enter monthly payment: ");
double monthly = double.Parse(System.Console.ReadLine());
double answer = Math.Ceiling((Math.Log10(monthly)-Math.Log10(monthly-borrowed*rate))/(Math.Log10(1+rate/12)));
Console.WriteLine(answer);
}
10的对数不能从负数中计算出来。我建议这个函数调用将使您的答案无效,因为它不是数字(NaN)。
Math.Log10(monthly-borrowed*rate)
再说一遍,这都是关于输入的。正如评论者所建议的那样,使用调试器逐步完成您的应用程序。
如果将复杂的表达式重构为组件:
double borrowed = 20000.00 ;
double rate = 6.00 / 100.00 ; // 6% interest
double monthly = 500.00 ;
double monthlyLog10 = Math.Log10( monthly ) ;
double monthlyPrincipal = monthly - borrowed * rate ;
double monthlyPrincipalLog10 = Math.Log10( monthlyPrincipal ) ;
double mpr = 1.0 + rate / 12.0 ;
double mprLog10 = Math.Log10( mpr ) ;
double delta = monthlyLog10 - monthlyPrincipalLog10 ;
double result = delta / mprLog10 ;
double answer = Math.Ceiling( result ) ;
您会发现,在这种情况下,monthly - borrowed * rate
实际上就是-700.0
。然后你会发现日志10(-700.00)是。。。NaN。
这就是你的问题。
如果你使用正确的公式,你会发现你的代码更简单:
double amountBorrowed = 20000.00 ; // A: the loan principal
double monthlyInterestRate = (6.0/100.00) / 12.0 ; // i: periodic interest rate (here, 6% per year / 12 to get the monthly interest rate)
double monthlyPayment = 250.00 ; // P: periodic payment
double totalNumberOfPayments = -Math.Log( 1 - ((monthlyInterestRate*amountBorrowed) / monthlyPayment) )
/ Math.Log( 1+monthlyInterestRate ) ;
你得到楠是因为Math.Log10(monthly - borrowed * rate))
Log10的定义区间为]0,+∞[.
if(monthly - borrowed * rate) < 0
未定义log10函数。
你的记忆力不好。
假设借款=B,利率=r,每月=m,月数=x。
如果r是手动速率,并且以百分比为单位:
Log(m) - Log(m - Br/12)
x = --------------------------------- r is the percent (ex 0.01)
Log(1 + r/12)
我想你得到(m-Br/12)<0,因为您忘记将r除以100