0

My code for greedy passes the check50 but when I manually enter -0.41 twice I don't get a re-prompt for another number. Am I missing another set of brackets or something to keep re-prompting until a positive number is entered?

//get amount of change owed 
    printf("How much change is owed?\n");
    float change_left = GetFloat();
    change_left = round(change_left*100);

    //reprompt if given a negative number
    if (change_left < 0)
     {
         printf("How much change is owed?\n");
         float change_left = GetFloat();
         change_left = round(change_left*100);
     }  
    while (change_left < 0);
0

The problem is your structuring. There are two different types of while loops. The more common is this:

while( test conditions are true)
{
    do some stuff;
}

The second is this:

do
{
    do some stuff;
}
while ( test conditions are true );

The first version will check the conditions at the start of each pass and will only execute the code between brackets if they are true. If the test is false initially, the code will not execute.

The second version is guaranteed to run once, even if the test condition is false at the start, because it does the test at the end of each pass.

Your code is actually executing the first block of code with GetFloat() and then the second block inside the IF statement brackets (assuming the test condition is true). When it gets to the while statement, the IF block has executed already and the while is a separate statement that follows the IF block. The structure is equivalent to this:

if (change_left < 0)
{
    .....
}

// and now, some new and separate code.
while( change_left < 0  )
{
     //nothing to do here
}

You could try something like this to replace all of your code and simplify it.....

// get change owed
do
{
     // a single block of "ask for the number" code here
}
while (change_owed < 0);

That should get you going. If you're satisfied with this, please mark the question as answered. Let's keep up on the forum maintenance. ;-)

| improve this answer | |
  • Hi Cliff B., I had tried a do while loop earlier but kept getting back errors whereas what I have above gave no errors other than not re-prompting after the 2nd negative input. Well after, playing around I realized that I wasn't identifying my get_change float correctly before initializing any loops but have now figured it out. – HMiddleton Apr 27 '15 at 18:16

You must log in to answer this question.

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