Path: csiph.com!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Sat, 25 Dec 2021 11:22:32 -0800
Organization: A noiseless patient Spider
Lines: 85
Message-ID: <864k6w1ocn.fsf@linuxsc.com>
References:
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="1fe31837ad76f46de1d32de2fe408cda"; logging-data="3928"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+gtAQLMe5+7HRILDFv43hh7W3qmh+N/BA="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:Y71lKbhb6fjzgtSvWwzDoy26G9E= sha1:UGwPeG/hMLTGDefaUwJjwKRFfN0=
Xref: csiph.com comp.lang.c:164067
Manu Raju writes:
[revised to repair spacing issues]
> #include
> #include
> #include
>
> int main()
> {
> float P = 100000; // Loan Amount
> float r = 7.5; // Advertised Interest Rate
> int n = 12; // Loan Period
> float payBack = (P * r / 1200 * pow(1 + r / 1200, n))
> / (pow((1 + r / 1200), n) - 1);
> float Opening = P; // Opening Balance
> float closing = 0; // Closing Balance
> float interest = 0;
> float Total = 0;
> float repaid = 0;
>
> printf("\nMonthly payment is: %.2f\n", payBack);
>
> printf("%10s %14s %13s %10s %14s %12s\n", "Month", "Beginning",
> "Interest", "Total", "Repayment", "Balance");
>
> for (int i = 1; i <= n; i++)
> {
> for (int j = 0; j <= n; j++)
> {
> interest = Opening * r / 1200;
> Total = Opening + interest;
> repaid = payBack;
> closing = Total - payBack;
> }
> printf("%10d %14.0f %13.0f %10.0f %14.0f %12.0f\n", i,
> Opening, interest, Total, repaid, closing);
> Opening = closing;
> }
> return 0;
> }
I gave some other comments in another response. Here is
a re-writing to make my suggestions more concrete.
(Note to all: Merry Christmas!)
#include
#include
static void show_payment_table( double, double, int );
int
main(void){
show_payment_table( 100000, 7.5, 12 );
return 0;
}
void
show_payment_table( double amount, double yearly_percentage_rate, int months ){
double const monthly_rate = yearly_percentage_rate / 100 / 12;
double const compounded = pow( 1 + monthly_rate, months );
double const adjustment = compounded / (compounded - 1);
double const payment = amount * monthly_rate * adjustment;
double balance = amount;
printf( "\nMonthly payment is: %.2f\n", payment );
printf( "%10s %14s %13s %10s %14s %12s\n",
"Month", "Beginning", "Interest", "Total", "Repayment", "Balance"
);
for( int i = 1; i <= months; i++ ){
double const interest = balance * monthly_rate;
double const owing = balance + interest;
double const remaining = owing - payment;
printf( "%10d %14.0f %13.0f %10.0f %14.0f %12.0f\n",
i, balance, interest, owing, payment, remaining
);
balance = remaining;
}
}