My assignment says to make a program to calculate the amount of change needed to add up to an input amount of money. Doesn't sound too hard, but there's problems somewhere. I initially tried using the modulus division (%), but it didn't give me correct results. I then tried receiving the input as a float, multiply by 100, and converting to a integer, but it gives strange results also. Through trial and error I figured out that when a number ends in >5, the actual number the program sees isn't what was input. Like, if i put in 1.38, it sees 1.379996, so when I change to an integer it cuts off the 9's and I'm always one off. Any ideas?
problems with float and int variables
Collapse
X
-
Floating point representation comes with its hazards. It's not possible in base 2 to represent all decimal numbers precisely.
My recommendation? Make your units in cents, not dollars. You never deal with a fraction of a cent, so you won't have to worry about floating point. -
Are you saying that if you have a dollar that you don't know how many cents you have??Originally posted by earlboomsso there's no way to convert dollars to cents?Comment
-
-
i tried that...refer to initial post. I scanf a float (ie 1.38), multiply by 100, and store the answer as an integer. Should give me 138, but it rounds to 137, because it actually gets stored as 1.379996. Is there anyway to fix this, or am I stuck with asking for cents instead of actual money?Comment
-
My suggestion is to have a string as input(e.g. thorugh char *argv[]);then to parse the string to determine properly all the units you need,e.g. dollars and cents;
something like this
user inputs 1.34
take what comes before the dot and convert it to an int,so you get "dollars"
take what comes after the dot and convert it to an int,so you get "cents"
never rely on dobule precision arithmetic when simple integer computations are needed.Good Luck!Comment
-
A float is floating point. Floating point rounds. If you don't want rounding, then don't use floating point. Because of this, you cannot write accounting applications using floating point. The rounding screws up the account balances. In some places there are actual laws against this.Originally posted by earlboomsI scanf a float (ie 1.38), multiply by 100, and store the answer as an integer. Should give me 138, but it rounds to 137, because it actually gets stored as 1.379996. Is there anyway to fix this, or am I stuck with asking for cents instead of actual money?
Personally, I would use an integer and keep everything in pennies. You can always display 150 as $1.50.
That decimal point is so enticing that beginners can't resist using floating point as a way to avoid writing code they have to think about. Then they spend hours with rounding issues, number of decimal places issues, etc.
You can avoid all of this by using integers.Comment
Comment