0

When I check through check50 I get everything right but 4.20. I think this has something to do with the order in which I wrote the part about typecasting (line 16)...is it that I need to round and THEN change from float to int? (I think right now it's written the other way around).If that's the case, or something similar, I'm not sure how to go about fixing that...so any suggestions towards that would be great! enter image description here

1

You have a couple of issues going on here, but you're on the right track.Yes, it has a lot to do with order of operations. Look at the line:

change_due = round ((int)GetFloat()*100));

The first thing that happens is GetFloat gets a float from the user and multiplies it by 100. Next, that result is cast as an int. But what happens during that process?

When a float is cast as an int, it is truncated! In the case of $4.20, after multiplying, the number is stored as something like 419.9999999999735 in the computer. When this number gets cast as an int, it is not rounded up, it is truncated to 419.

Next, the 419 is rounded to 419, but the result is stored as a float, so it's stored approximately as 419. (I'll leave it to you to determine exactly what that stored value is.) Finally, the result is stored in change_due, which itself is a float, so there's still the problem with storing an approximated number.

So, if you want to make this work, the casting to an integer should be the last thing done, not an intermediate step. Then, the result needs to be stored in an int, not a float.

If you really want to see what's going on, you can always break the combined calculation statement into multiple statements and print out the intermediate results using formatted output that will display at least 12 to 16 digits to see what is really being stored in the floats.

This should get you going. If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .