0

I am receiving this output from check50 on pset1 cash.c

:) cash exists
:) cash 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
:) input of 1.6 yields output of 7
:) input of 23 yields output of 92
:( input of 4.2 yields output of 18
    expected "18\n", not "22\n"
:) rejects a negative input like -.1
:) rejects a non-numeric input of "foo"
:) rejects a non-numeric input of ""

So I see 4.2 as input is outputting an invalid value. Then I ran debug50 and set a breakpoint to where get_float is being called, and I see the the float is being set to 4.19999981 instead of 4.20000000. Reading the bottom of the spec, I see the note

"And so, before making change, you’ll probably want to convert the user’s input entirely to cents (i.e., from a float to an int) to avoid tiny errors that might otherwise add up! Of course, don’t just cast the user’s input from a float to an int! After all, how many cents does one dollar equal?"

So I am multiplying the user inputted float by 100 and storing it as an int. But that is turning 4.2 into 419, since 4.2 is becoming 4.19999981. Using the round function in math.h as also mentioned in the specification, 4.2 is being rounded to 4. The CS50 reference for the round function makes no mention of how to round up to 2 decimal places. What am I doing wrong?

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
{
    float f;
    int i;
    do
    {
        printf("Change owed: ");
        f = get_float();
        f = roundf(f);
        i = f * 100;
    }
    while(f <= 0);

    int c = 0;

    while (i >= 25)
    {
        i = i - 25;
        c++;
    }

    while (i >= 10)
    {
        i = i - 10;
        c++;
    }

    while (i >= 5)
    {
        i = i - 5;
        c++;
    }

    while (i >= 1)
    {
        i = i - 1;
        c++;
    }

    printf("%i\n", c);

}

1 Answer 1

1

You already understand all the parts of what's happening. Time to put them all together.

The round function always rounds at the decimal. It's a simple fix. Move the decimal before you round. Don't round before you move the decimal (as the code does now.)

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

1
  • Is this by any chance faster than the submitted code? Feb 18, 2021 at 9:59

You must log in to answer this question.

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