0

My code at least appears to similar to others' I have seen on here, but I can't seem to get the right answers. If I enter anything less than "1" I get "0" for the number of coins, and if I enter "1.25" I will get four coins.

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

int get_change();

int main(void)
{
   float change = get_change();
   change = round(change*100);

   int coins=0;
   while(change>=25)
   {
       change-=25;
       coins++;
   }

   while(change>=10)
   {
       change-=10;
       coins++;
   }

   while(change>=5)
   {
       change-=5;
       coins++;
   }

   while(change>=1)
   {
       change-=1;
       coins++;
   }

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

}

int get_change (void)
{
    float n;
    do
    {
        printf("How much change is owed?\n");
        n = get_float();
    }
    while (n<0);
    return n;
}
0

You have two serious issues. First, the get_change() is flawed. It gets a float, but returns an int. When it returns that int, it truncates it at the decimal point, it doesn't round it off. Any fraction of a dollar is truncated or deleted. That means that anything less than $1.00 will return 0 and anything larger will only return the whole dollar value.

Once the problem above is fixed, there's still the most common problem with this pset and the whole point of the exercise. Using a float to store the change as you calculate through is a problem. See http://cs50.stackexchange.com/questions/19096/pset1-greedy-failing-at-one-value/19098#19098 for a more complete explanation.

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

You must log in to answer this question.

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