0

When I input an amount into the program cash, it gives me one more coin than I should have and I'm not sure how to fix it

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

//Prompt user for the amount of change owed in dollars
int main(void)
{
    //Initialize variable 'Change Owed'
    float Change;

    do
    {
        Change = get_float("How much change is owed in dollars?: ");
    }
    //Invalid values for change owed to reprompt user
    while(Change <= 0);

    //Convert dollars to cents, to the nearest penny
    int cents=round(Change*100);
    //Initialize coin values
    int quarter=25;
    int dime=10;
    int nickel=5;
    int penny=1;
    int coins=1;
    
    //Track quarters
    while(cents >= quarter)
    {
        cents=cents-quarter;
        coins=coins + 1;
    }
    
    //Track dimes
    while(cents >= dime)
    {
        cents=cents-dime;
        coins=coins + 1;
    }
    
    //Track nickels
    while(cents >= nickel)
    {
        cents=cents-nickel;
        coins=coins + 1;
    }
    
    //Track pennies
    while(cents >= penny)
    {
        cents=cents-penny;
        coins=coins + 1;
    }
    
    //Print amount of coins
    printf("%i\n", coins);
}
  • What appears to be the problem? Does it compile? Does it give output? Is the output wrong? What is wrong about the output? This is what is known as a naked code drop - code that is posted with little or no explanation - and is against the rules of this forum. Please edit your question and add some explanation and context to your question. – Cliff B Jul 17 '20 at 20:45
  • @CliffB My apologies, I edited the question to specify my issue. – Liz-Sod497 Jul 17 '20 at 21:11
  • Better. ;-) This is about correcting errors for the future, not accusing anyone. I've further edited your question to format the code and to show a better way to ask the question and post a headline. Now, give me some time to look at the code. ;-) – Cliff B Jul 17 '20 at 21:20
-1

This is an easy one. Coin count is off by one all the time, right?

The variable coins is used to count the number of coins counted. What is it initialized to, 1 or 0?

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

  • Oh I see, I had it initialized to the wrong number- I changed it and it works now. Thank you for your help! – Liz-Sod497 Jul 17 '20 at 21:24

You must log in to answer this question.

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