![]() |
OT: More Elementary C++ Madness
Purpose: Determine least amount of coins and bills for change.
Specific problem: value returned. ~~~ double change, money, bill; int hundred; //includes more variables but hundred will suffice for this example change = money - bill; //user inputs both values in the form 123.45 change = change * 100; //to convert everything to pennies value = int(change); ~~~ Using the example of a bill of $65.87 and money of $100.00, yields: change = 34.13 change = 3413 value = 3412 !!!!!!!!!!!!!!!!!! hundred = value/10000; //returns integer equating to #of bill required value = value - (10000 * hundred); //calculates remaining change Can anyone explain why the cast is causing this to happen, and more importantly, how I can prevent it? When you get down to the dimes, nickels and pennies, it throws everything off. |
That one's a head scratcher. When I do 65.80, it comes out right. I have no idea why it sends it down to 3412. Weird. I tried a couple of things, but nothing worked.
|
Yeah. It took me a long time to realize that the cast expression was the problem because my instructor specifically told me to use it to convert from float to int. I was using cout statements checking everything BUT value = int(change).
Somewhere along the way I'm supposed to use modulus division to carry the remainder but that's pretty pointless if the initial data type conversion doesn't work. I don't think I'll complain about anyone's text sims anymore. :D |
Your problem is the same one I noted in the other post about floating point math -- you have to be careful about rounding. 34.13 happens not to be exactly representable in your computer (when multiplied by 100, it's stored as 3412.9999999999995 [from my watch window]). And casting doesn't round, it truncates. If you want to round, you have to do so explicitly -- try adding 0.5 to change. You'll still run into corner cases, but not for the stuff that your interested in right now.
On a pedantic note, if you're doing C++, you should (strictly speaking) be using static_cast rather than (unsafe) C-style casts. (OK, I'm being a little pedantic, I still use C-style casts for arithmatic stuff, but I never use them any other time.) |
Here's an example program that exhibits the correct behavior:
Code:
#include <iostream>Edit: It tried to parse the includes as HTML. Doh! |
Or...
Code:
#include |
Thanks, guys. It's starting to make sense. Representation at the bit level is something I have to keep in mind. From now on I think I'll do a bunch of cout statements early to see what values are actually being generated and then go from there.
|
| All times are GMT -5. The time now is 10:45 AM. |
Powered by vBulletin Version 3.6.0
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.