简体   繁体   中英

Credit Card Equation (in C#)

I have a homework question that I need some verification on. I got the correct answer for the first part of the question. However, the second part of the question isn't working out so well. I'm not sure if my calculations are off or if the test data is wrong. (it's happened a few times already this year) .

We are suppose to design a console application that will solve how many months it'll take to pay off a loan.

I can't use any code I haven't learned yet; just basic code. (no loops, arrays, etc)

The formula is: N = -(1/30) * ln(1+b/p(1-(1+i)^30)) / ln(1+i)

n = months

ln = log function

b = credit card balance

p = monthly payment

i = daily interest rate (annual interest rate/365)

Test Data for Question 1:

Credit Card Balance: $5000

Monthly Payment: $200

Annual Rate: 0.28

My answer: 38 months

Test Data for Question 2:

Credit Card Balance: $7500

Monthly Payment: $125

Annual Rate: 0.22

Unable to get an answer

My solution:

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

Your problem is that you try to take the logarithm of a negativ number. Thats why you get "NaN" (not a number) as a result.

But why is 1+b/p(1-(1+i)^30) negative in the second example? Well, that is simple. Because your monthly interest is greater than your monthly payment!

$7500 * 0.22 / 12 = 137.5$

Since your monthly payment is just $125, you will take an infinite amount of months (speak: never) to pay of your debt.

NaN is the programming languages way to represent a non-computable result.

So, you don't have a programming problem, you have a debt problem. Maybe this is a question for money.stackexchange.com ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM