aanngaa
aanngaa

Reputation: 48

to calculate remaining loan balance

I am trying to write a program in C to calculate the remaining balance after 1st, 2nd & 3rd monthly payments, given the loan, monthly payment amount, and interest rate. I am having a problem in entering the input (floating point numbers) i.e it only takes one input (loan) & displays the answer without considering the other 2 inputs (interest rate & monthly payments).

This problem occurs only when I use the floating-point numbers (even in other programs also). I want to ask if this is due to coding or due to any other reason.

My code is as follows:

#include<stdio.h>    
main()    
{    
   float loan,interest,monthly_payment;      
   float balance_Imonth,balance_IImonth,balance_IIImonth;    

   printf("Enter the amount of loan: ");  
   scanf("%.2f",&loan);  

   printf("Enter the amount of interest: ");  
   scanf("%.2f",&interest);  

   printf("Enter the amount of monthly payment: ");  
   scanf("%.2f",&monthly_payment);   

   balance_Imonth=((interest/(100*12))*loan)+(loan)-(monthly_payment);  
   balance_IImonth=((interest/(100*12))*loan)+(balance_Imonth)-  (monthly_payment);  
   balance_IIImonth=((interest/(100*12))*loan)+(balance_IImonth)-(monthly_payment);  

   printf("Balance remaining after I payment:   $%.2f\n",balance_Imonth);  
   printf("Balance remaining after II payment:  $%.2f\n",balance_IImonth);  
   printf("Balance remaining after III payment: $%.2f\n",balance_IIImonth);  
}    

Upvotes: 0

Views: 729

Answers (1)

R Sahu
R Sahu

Reputation: 206667

The format specification "%.2f" is OK for printf but not for scanf. Use just "%f".

In your program, all the scanf function calls fail. You are just seeing undefined behavior due to use of uninitialized variables.

Always check the return value of scanf to make sure that the operation succeeded before you proceed to use the variables in which scanf stores the results.

Use

if ( scanf("%f", &loan) != 1 )
{
  // Deal with error.
}

Upvotes: 3

Related Questions