0

So I have an assignment to create a change maker. I pretty much got it down, I just have one problem. Everything goes fine until it get to dividing the last iteration of the loop. If I use 55.87 as a value once the loop get to the last .02 and divides it by .01 (to hopefully get 2) it gets 1 instead. Here is my code:

#include <stdio.h>

int main (void)
{
    double money;
    double change[8] = {20, 10, 5, 1, .25, .10, .05, .01};
    int quantity;
    int i;
    int rpt = 1;

    printf("Kevin Welch - Assignment 2 - Change Maker");

    while (rpt == 1)
    {
        printf("Enter a dollar amount up to 200 to make change.\n");
        printf("Maximum of two decimal points for cents.\n");
        scanf("%lf", &money);

        while (money > 200 || money < 0)
        {
            printf("Not a valid value.\nPlease re-enter:\n");
            scanf("%lf", &money);
        }

        printf("\nAmount entered: $%.2lf\n\n", money);
        printf("Change breakdown:\n");

        for (i = 0; i < 8; i++)
        {
            quantity = (money / change[i]);

/*
 I added this next printf line to output my variables to see what they        
 were doing while in the loop. 
 Output shows money = 0.02 and change[i] = 0.01, 
 however (money/change[i]) = 1 instead of 2.
*/

            printf("\n%.2lf  %i   %.2lf\n\n", money, quantity, change[i]);

            if (quantity >= 2 && money != 0)
            {
                if (change[i] >= 10)
                    printf("%i $%.2lfs\n", quantity, change[i]);
                else
                    printf("%i  $%.2lfs\n", quantity, change[i]);
                money -= quantity * change[i];
            }
            else if (quantity >= 1 && money != 0)
            {
                if (change[i] >= 10)
                    printf("%i $%.2lf\n", quantity, change[i]);
                else
                    printf("%i  $%.2lf\n", quantity, change[i]);
                money -= quantity * change[i];
            }
        }
        printf("\nWould you like to use the change maker again?\n");
        printf("Enter 0 for No and 1 for Yes:\n");
        scanf("%i", &rpt);
        while (rpt != 0 && rpt !=1)
        {
            printf("Enter 0 for No and 1 for Yes\n");
            scanf("%i", &rpt);
        }
    }
}
Kevin Welch
  • 1,488
  • 1
  • 9
  • 18
  • 1
    And in your particular example, most people would recommend that you use integer math and make the value `1234` mean 12 dollars and 34 cents. – Bill Lynch Mar 01 '15 at 22:32
  • To fix the problem change your code to use `unsigned long` or some other integral type, instead of `double`, and this will represent the number of cents. It will make the `scanf` line slightly more complicated. – M.M Mar 01 '15 at 22:32

0 Answers0