Small bug in my short C code. Why?

后端 未结 3 1108
不思量自难忘°
不思量自难忘° 2021-01-23 12:11

I can\'t figure out why this works for 90% of the inputs, but not the others. It is meant to tell you how many coins you would get back in change. Most test amounts work fine,

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-23 12:42

    The closest float value to 4.20 is slightly smaller than that (4.19999980926513671875, for the usual 32-bit IEEE754 floats). So after you subtracted the $4 from the 16 quarters, you have an amount left that is slightly smaller than 0.2. Dividing that by 0.1 results in a value slightly smaller than 2, so your nickels value is 1. The same happens then after you subtract your nickel, the value is slightly smaller than 0.1, dividing by 0.05 results in a quotient slightly smaller than 2.

    You should use integers only for such a computation, calculating in cents.

提交回复
热议问题