Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Oct 25, 1999

Calculating interest without floating types

Question:
How can you caluculate interest using only integers and no double or floats?

Answer:
This question can be of interest for anyone who is confined to ineteger arithmetic. Many embedded systems and specific processors do not support floating data types. On some processors, which happen to support floating data types, the performance penalty of using these types is unacceptable so the user is forced to use only integer arithmetic.

The technique relies on multiplication by a factor of 100 before you apply interest rate calculation, and division by 100 after the calculation has been done. Thus, if you want to increase a balance of $200 by 5%, you take the factor 1.05 and multiply it by 100. The result, 105 is an integer. You then perform the interest calculation as follows:


temp = 105 * 200; 
Having performed the calculation, you now divide the result, 21000 by 100:

result = 21000/100;
The result is 210, which is what you get when you increase 200 by 5%.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date