I wanted to create a loan calculator, but the code I could think of was using 3 functions, and calling them and getting result. But I felt it was easy but bad code because I thought this can be written in fewer lines and with more quality. I wanted to ask what are some things to keep in my mind while trying to write better code instead of going in flow and creating many functions.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
float loanAmount,interestRate,Discount,i,loanPayment; //global variables
int years;
void loanDetails(void); //input from user regarding the loan
float annualRate(void);// interest rate
float discount(void); //discount to be added
int main() //main
{
loanDetails(); //called three functions
annualRate();
discount();
loanPayment = (loanAmount)/(Discount); //formula for monthly payments
printf("\nthe monthly loan payment is %f",loanPayment);
return EXIT_SUCCESS;
}
void loanDetails(void) //taking input from user
{
printf("please enter Total Loan Amount: ");
scanf("%f",&loanAmount);
printf("please enter the number of years: ");
scanf("%d",&years);
printf("please enter the annualrate to be applied: ");
scanf("%f",&interestRate);
}
float annualRate(void) //calculated annual rate
{
float *ann;
ann = &interestRate;
i = ((*ann)/(100))/12;
printf("the value for %d years is %f",years,i);
return i;
}
float discount(void) //calculated dicount
{
float *x,y;
x = &i;
y = 1 + *x;
int n = years*12;
float topD = (pow((y),n)-1);
float botD = (y-1)*pow((y),n);
Discount = topD/botD;
printf("\nthe value of discount is : %f",Discount);
return Discount;
}
i = ((*ann)/(100))/12;
, which implies you're calculating a monthly rate because you're dividing by 12. You're also relying too much on global variables instead of utilizing function parameters. \$\endgroup\$ – AleksandrH Feb 24 '19 at 1:46