CS50 Greedy Need Advice

后端 未结 2 842
误落风尘
误落风尘 2021-01-29 06:39

I am doing the cs50 problem set \"Greedy\". Basically asking the user for how much change is owed and then outputting the minimum amount of coins that can equal the inputed amou

2条回答
  •  醉酒成梦
    2021-01-29 07:19

    It looks like this is an issue with the conversion from float to int. When you try to convert from dollars to cents, you do so with this line of code:

    int cents = (int)(n * 100);
    

    However, this line of code, for $4.20, is returning a cent value of 419. This is a problem with rounding and floats, as 4.2 * 100 is returning 419.99999999 instead of 420.0000000, and integer casting truncates instead of rounding. This problem also occurs with $4.18, and probably other values as well.

    To prevent this, add 0.5 before the cast, like so:

    int cents = (int)(n * 100 + 0.5);
    

    This will ensure that the rounding takes place in the proper direction, as you are never off by more that a trivial float error.

    Using the math.h library, you could also use the roundf() function, which will work in the case of negative numbers, just in case.

    int cents = (int)(roundf(n*100));
    

提交回复
热议问题