|
|||||||
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
#1 |
|
Member (4 bit)
Join Date: Sep 2004
Posts: 13
|
Figure out my C++ program's problem. YOU CAN FIND THE MISSING PENNY!
I have a program in C++ that lets users enter in the amount of a purchase and the amount they paid. It will then calculate their change in dollars, quarters, dimes, nickels and pennies. Here it is:
PHP Code:
2.75 / 1 = 2.75, casted to an int, drops the decimal changeDollar = 2 2.75 - (1.00 * 2) = .76 So my algorithm broke down the dollars. .76 / .25 = 3.04, casted to an int, drops the decimal changeQuarter = 3 .76 - (.25 * 3) = .1 Now we're down to one penny. It'll continue to do this until it gets to the pennies and eventually finishes. Now, for all my test data, the output is logically correct. HOWEVER, when I enter 50.00 for the purchase amount and 50.01 for the amount paid, the result says this: Your change is $0.01 You should be paid in... 0 dollars, 0 quarters, 0 dimes, 0 nickels, 0 pennies It's off by a penny. Why??? It works when I do total 100 and 100.01 paid. In fact, it even works when I enter 20 and 20.01 paid. I'm almost tempted to write a loop to try every value up to 500 to see how many are off by a penny. What's going on? :O Last edited by aKobrakai; 06-10-2005 at 09:08 AM. |
|
|
|
|
|
#2 |
|
Member (9 bit)
Join Date: Feb 2005
Posts: 392
|
C++ floating point is incapable of exactly representing most decimal fractions, regardless of the choice of precision
Use a BCD library( Binary Coded Decimal) we, engineers have a saying: "precision arithmetic calculations are best done by FORTRAN( computer language/compiler)" and "dont subtract two number of similar magnitude." |
|
|
|
|
|
#3 |
|
Member (11 bit)
Join Date: Aug 2003
Location: NJ
Posts: 1,099
|
Even the program we use at work (Portfolio Accounting System) is off a penny some of the time (sometimes even up to 15 cents). We use 6-8 decimal places. We deal with billions of dollars and we usually make an adjusting entry to reconcile it out.
I also had the same problem back then when I was taking an Assembly class.
__________________
P4 2.6C @ 3.12 || ASUS P4C800-E Dlx || Antec SOHO File Server w/ 5 case fans || Antec TruePower 430w PSU || 2 x 512MB Crucial PC3200 DDR || 280GB of total storage 7200rpm ATA100 8mb cache || LiteOn CDRW 52x32x52 || LiteOn DVD+/-RW SOHW-812S || WinXP Pro || Solarism 15" TFT LCD || 500VA TrippLite UPS || Logitech MX-700 Duo || ATI 9800 AIW || Sennheiser HD-555 |
|
|
|
|
|
#4 | |
|
Member (9 bit)
Join Date: Feb 2005
Posts: 392
|
Quote:
Last edited by alfie2; 06-13-2005 at 02:49 PM. |
|
|
|
|
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|