控制台一直给我NAN

时间:2014-09-16 21:10:57

标签: c# nan

我的回答有类似的问题,但情况并不完全相同。我正在制作贷款偿还计算器但是当我运行这个迭代时,我会收到" NaN"无论我使用什么数字。我不确定我的数学是错误还是我误用了数学。"功能。

    int choice=1;
    do{
        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);

3 个答案:

答案 0 :(得分:3)

10的对数不能从负数计算。我建议这个函数调用将你的答案视为非数字(NaN)。

Math.Log10(monthly-borrowed*rate)

然后,这一切都与输入有关。正如评论员所建议的那样,使用调试器逐步完成您的应用程序。

答案 1 :(得分:1)

由于Math.Log10(monthly - borrowed * rate))

,你得到了南

Log10的定义间隔为0,+∞[。

if(monthly - borrowed * rate) < 0未定义log10函数。

你的alogorthm不好。

假设借用= B,rate = r,monthly = m和month number = x。

如果r是年龄,并且是百分比:

        Log(m) - Log(m - Br/12)
x = ---------------------------------   r is the percent (ex 0.01) 
                  Log(1 + r/12)

我想你得到(m-Br / 12)&lt; 0因为你忘了将r除以100

答案 2 :(得分:1)

如果您将复杂的表达式重构到其组成部分中:

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。然后你会发现log 10 ( - 700.00)是...... NaN。

因此你的问题。

如果您使用correct formula,则会发现您的代码更简单:

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 ) ;