0

I finished the challenge and my first C code worked apparently well, returning each time the correct minimum number of coins needed for change. Then when I tried to "clean it up" a bit and remove a redundant printf, everything seems to go to wrong. I cannot get my brains around this one, I am very confused... Why does this happen?

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

int q = 25; //variable for quarters
int d = 10; //dimes
int n = 5;  //nickels
int p = 1;  //pennies

int x;  //variable for final result
int r;  // variable for the reminder

float amount(string prompt);

int main(void)
{
    float a = amount("Enter dollar amount with format 0.00: $");
    int cents = round(a * 100);
    printf("Your input: $ %.2f", a);
    // printf(", which amounts to %i total.\n", cents); //WHY DELETING THIS LINE MESSES UP WITH THE FLOAT AND THE RESULT?

    x = cents / q;
    r = cents % q;

    x = x + (r / d);
    r = r % d;

    x = x + (r / n);
    r = r % n;

    x = x + (r / p);
    printf("%i\n", x);
    r = r % p;
    printf("%i\n", r);
}

float amount(string prompt)
{
    float a;
    do {
        a = get_float("%s", prompt);
    }
    while (a <= 0);
    return a;
}
1

Could it be the missing line break? The output of

printf("Your input: $ %.2f", a);
printf(", which amounts to %i total.\n", cents);

or equivalently

printf("Your input: $ %.2f, which amounts to %i total.\n", a, cents);

ends in a newline \n, so the next number would be placed on the next line. Without that second part, whatever you print next gets printed directly behind the float, looking as if it were extra digits.

1
  • Thank you so much.. After you mentioned it and have a look at it again it seems so obvious!! I would look at that extra digit as something broken and it was really that simple. Been learning now for one month first with html and css and now CS50, one of the most humbling experiences I remember so far haha Thanks again Jun 19 '19 at 13:04

You must log in to answer this question.

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