|
-
Reef Shark
float degradation
Creating a simple change counting program in C++ (example: enter a money amount less than 100 dollars...and the program will make change, telling how many tens, fives, ones, etc.)
I've noticed that when dividing the number by 1 in order to derive the number of ones, I get a repeating decimal amount, such as infinite precision is not there with a float (binary, base 2 instead of base 10, is the cause, I'm assuming).
How can I fix this problem? Basically, when I perform this operation:
1.12 - 1 = .1199999999
This may seem confusing so here's the code I'm working on...
// begin ones routine
int ones;
ones = money / 1; /* int money to remove decimal */
// substr and setw on next cout for formatting and doesn't pertain to my problem
cout << ones << setw(8) << " ones" << " " << setw(0)
<< bars.substr(0,ones) << endl;
money = money - ones; /* subtract ones from total*/
bash-2.03$ specs
[windows]xp pro running on
[ecs]K75SA
[amd]athlon xp 1800+
[nvidia]ati radeon 9200
[crucial]512mb pc133
[wd]80 gig, 120 gig
[philips]15" 150 B2 Flat-Panel
[yamaha]crw2400 16x10x40x
[pioneer]slot 16x40x
[soundblaster]live mp3+
-
Mako Shark
Well i dont recigonize that type of code, but then again about all i know is some java.
Ok, a little off topic, if you dont understand the binary system and roundoff error then your should probably read this, its pretty interesting
Your problem is that your floating point is running out of precision, im not sure what the amount of digits a C++ floating point can handle.
Anyways, the way to avoid this is to multiple everything by 100 (to get rid of the decimal), and then when your done with your calculations and want to present it divide it by 100 to get your cents back.
Or you could use a larger floating point type number, however the first method is probably the most easy as you dont have to keep remembering the number of signifigant decimal digits that the floating point type your using can hold without getting round off error.
In fact i believe banks multiply their money by 100,000 so they end up with thousandth of a cent, they use the 1/1000ths of a cent to accuratly caclulate intrest.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|