Bad Mortgage Calculation Code

Hello,

I'm teaching myself C and attempting to write a little program that will calculate the monthly payments on a fixed-rate mortage:

/* Aaron's mortgage foo */
// mortgage.c
#include <stdio.h>
#include <math.h>

int main(void)

{
float interestRate; // The bank's fixed interest rate
float interest; // monthly interest rate
int mortgage; // Cost of the house
int term; // How many years is the mortgage
int totMonths; // total number of payments
float monthlyPayment; // Your monthly mortgage payment

interest = interestRate / 1200;
totMonths = term / 12;
 
  printf\("How much is the mortgage? "\);
  scanf\(" %d", &mortgage\);

  printf\("For how many years? "\);
  scanf\(" %d", &term\);

  printf\("What is the bank's interest rate? "\);
  scanf\(" %f", &interestRate\);

monthlyPayment = mortgage * pow\(1 \+ interest, totMonths\) * interest / pow\(1 \+ interest, totMonths\) - 1;

printf\("Your monthly payments are %.2f\\n.", monthlyPayment\);
return 0;

}

When I fat-finger the numbers into a calculator I get correct answers so I think monthlyPayment formula is accurate; however, program outputs monthly payments of -1.00 no matter what numbers I input. Obviously, I'm overlooking something. Any help? Thanks.

One, the number of months is the term * 12 not divided by 12.
Secondly it appears that you are using interest and totmonths before interestRate and term have been given values.
Move all the assignment statements to after the scanf statements.

 interest = interestRate / 1200;
totMonths = term / 12;

What is the value of interest and totMonths when it is executed ?

You are using the variables once they are declared and no value assigned to them !

interest is interestRate converted to a decimal (i.e. 7% = 0.0058) for arithmetic purposes. Is there a C function that accomplishes this?

totMonths is simply the term of the mortgage. I want the user to input their mortgage in years and let the program convert it to months.

I moved the variable declarations beneath the scanf() statements and fixed the totMonths (duh! :o ) and the program seems to work. However, I don't think the monthly payments are correct. For $100,000, 30 yr, at 6% it outputs $499.00/mo. However, web-based calculators give $599.50/mo. Obviously, something in the monthlyPayment algorithm is not quite right. Does the order of operators make sense?

Thanks for the help!

float interestRate=0.;
float interest=0.; 
int mortgage=0; 
int term=0; 
int totMonths=0; 
float monthlyPayment=0.; 

This is what Matrix is talking about. You have to initialize varaibles.

monthlyPayment = mortgage * pow(1 + interest, totMonths) * interest / (pow(1 + interest, totMonths) - 1);

Aha! I always miss a couple of parens. Good thing I don't write LISP.

Well, thanks to your help, folks, I now have a working C program...my first! :cool:

Viel danke!