algorithm - a lot of decimal value storage in C++ -


i wanted write program returns how many months survive when we're given our monthly expenditure, amount of disposable income, , interest rate (all in integers). instance, if start disposable income = 1000, interest rate = 5%, monthly expenditure = 100,

after first month: 1000*1.05 - 100 = 950, have 950 dollars left after second month: = 950*1.05 - 100 = 897.5  

and on, , in end, can survive 14 months.

i wrote following code in c++:

int main(){  int i=0; int initialvalue; int interest; int monthly;  double value=1.0*initialvalue; double r=1+1.0*interest/100; while(value > 0){     if(value < monthly){         break;     }     else     {     value=value*r-monthly;       i++;     } }; cout<<i; return 0; } 

but sufficiently large values of initialvalue , small values of monthly, program wrote runs degree it's unusable. there problem code makes run not (or slow)?

any appreciated.

double cannot store numbers precisely. 1 consequence of when subtract small number large number, result not changed original large value.

one solution problem use int calculations. think of values number of pennies, rather number of dollars.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -