0

Can you please, help with some dvice: greedy stops working after it turns dollars into cents - how can I make the link between the functions? My code looks like that so far:

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

int main(void)
{
    int cents = 0;
    int count = 0;

    printf("How much change is owed:\n");
    float amount = GetFloat();

    cents = (int)round(amount*100);

    if(cents > 0)
    {
        while(cents > 25)
        count++;
        {
            while((cents-25) > 10)
            count++;
            {
                printf("You get %d coins!\n", count);
            }
        }
    }

    else
    {
        printf("please, give a positive value:\n");
    }
    return 0;
}

I did it only for 25 and 10 cents as I need to find the bug first, maybe I am on entirely wrong route....

1 Answer 1

1

The code structure is creating an infinite loop. Look at the following:

    while(cents > 25)
    count++;
    {
        ...
    }

A while command will only execute the code inside the curly braces if they immediately follow the while statement. If a simple statement that ends with a semicolon immediately follows the while statement, that is what will execute. In the code above, the count++; statement is the code that is controlled by the while statement, not the code in the curly braces. The code in the curly braces will always execute and will only execute once, because it is not associated with the while command.

The while loop structure should look like this:

while ( test_condition  )    // no code between while statement and {
{
    // lines of code go here.
    ...
}

But, if change is ever greater than 25, the code goes into an infinite loop because there's nothing in the loop that changes the value of change to be less than 25.

Fix those issues and it'll get you started. No guarantees that there aren't other problems coming.

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

2
  • Hi Cliff - thanks! Basically, this is what I am trying to do - to associate the code in the curly braces with the while statement and don't really understand how........I think also that there are some syntax errors, which I am trying to fix, but keep going in circles - can you please, give a tip how to do that? Thanks!
    – SnezhinaT
    Commented Apr 25, 2016 at 17:08
  • Ummm..... I just did. If the answer doesn't explain it well enough, spend some time reviewing the class lectures and videos, and perhaps google while loops to get more.
    – Cliff B
    Commented Apr 25, 2016 at 17:18

You must log in to answer this question.

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