0
Compound Interest Program. Plz how to print the last rate *0.120*; it print only until rate 0.115
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { double amount; double principal = 5000; double rate; unsigned int year; for (rate = 0.1; rate <= 0.120; rate += 0.005) { printf("Rate: %.3f\n\n", rate); printf("%6s%30s\n", "Year", "Amount on deposit"); for ( year = 1; year <= 5; year++ ){ amount = principal * pow( 1.0 + rate, year ); printf("%6u%30.3f\n", year, amount); } printf("\n"); } return 0; }
1 Respuesta
+ 1
Kit D. Cat pointed out an important technique to know when using floating point in loop control.
There are few more lessons we can glean from this.
1) Double precision is not always best. I found empirically that float will give a better result.
2) Beware that adding a float value repeatedly can accumulate rounding error. For less rounding error, use a whole number loop counter and multiply the float by the counter.
With these changes, I got the rate to match 0.120.
float amount;
float principal = 5000;
float rate, i;
unsigned int year;
for ((rate = 0.1, i = 0.0); rate <= 0.120; rate = 0.005*(++i) + 0.1) {
3) Rounding the comparison to the desired significant digits solves the problem in both float and double.
for (rate = 0.1; round(1000.0*rate) <= 120.0; rate += 0.005) {
And now combining ideas from both 2) and 3) for the most accurate computation in either float or double, the loop should be:
for ((rate = 0.1, i = 0.0); round(1000.0*rate) <= 120.0; rate = 0.005*(++i) + 0.1) {