0

For some reason, everytime I run my code the result gives me a multiple of 4, is it rounding to 0.25 cents everytime? I checked the code with other users and it seems fine the rounding part...

./greedy Change: 1 Coins used: 4

./greedy Change: 5 Coins used: 20

./greedy Change: 10 Coins used:40

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

float in;
int out = 0;

int main(void){

    do{
        printf("Change: ");
        in = get_float();
    }
    while (in < 0);
    //round amount
   in = round(100 * in);

    while(in >= 25){
        in -= 25;
        out++;
    }
    while(in >= 10){
        in -= 10;
        out++;
    }
    while(in >= 5){
        in -= 5;
        out++;
    }
    while(in >= 1){
        in -= 1;
        out++;
    }
    printf("Coins used: %i\n", out);

}
1
  • Just some spacing problems improved because of the copy-and-paste here, but the code still gives me the same results
    – rotciv
    Commented Feb 2, 2017 at 15:04

2 Answers 2

0

Greedy.c is outputting what it should - if you walk through the program with in at 1, 5, 10, you should expect out to be 4 quarters, 20 quarters, and 40 quarters, respectively. (1 divided by 0.25 is 4, 5 divided by 0.25 is 20, etc.)

printf("Coins used: %i\n", out); is causing you to fail check50. You see, check50 is expecting a number, not Coins used: ... Though Coins used: may help the user understand your program, check50 is very strict and wants a number (in this case, out), not a string like Coins used:. This should push you in the right direction.

If this answers your question, hit the green checkmark! Don't forget to comment below if you still have issues/questions.

0

Your code is doing what it's meant to. For 1 dollar, it's returning 4 quarters, for five dollars, it's returning 20. Try some more odd value for input, like 0.87 (3 quarters, 1 dime, 2 cents => 6 coins).

I somewhat dislike that you store the now-integer number of cents in a floating point variable again, but that does not cause any problem here for reasonable inputs, is just inefficient.

You must log in to answer this question.

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