0

I am stuck at pset 1 - greedy. I only receive a wrong output at the values 1.6 and 0.15. At both outputs the value is by one to high.

:) greedy.c exists

:) greedy.c compiles

:) input of 0.41 yields output of 4

:) input of 0.01 yields output of 1

:( input of 0.15 yields output of 2 \ expected output, but not "3\n"

:( input of 1.6 yields output of 7 \ expected output, but not "8\n"

:) input of 23 yields output of 92

:) input of 4.2 yields output of 18

:) rejects a negative input like -.1

:) rejects a non-numeric input of "foo"

:) rejects a non-numeric input of ""

I have no clue what the reason is for that. Is there anybody who could help me? Thanks!

Here is my code:

enter image description here

1 Answer 1

1

I don't understand the line double round(double change);.

Don't use floating point numbers when dealing with money, as a floating point number cannot exactly represent numbers that are not multiples of a power of 2. 0.75 would be 3*0.25, can be stored in a float, but 0.1 cannot, and will be rounded to some seemingly random slightly off value.

Convert to an integer representing the number of cents instead, with some rounding like int cents = round(100 * dollars); (don't forget to include math.h, and maybe specifying -lm to the compiler if your make file doesn't provide the switch already).

1
  • Thanks, it worked :)
    – Liz
    Commented Mar 14, 2017 at 13:53

You must log in to answer this question.

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