0

When I try to run my code, I get prompted for the change amount, as desired, but when I enter an amount, nothing else appears in the terminal and the program does not calculate the minimum number of coins as it should. I suspect the problem is related to my do-while loop, but I'm not sure and don't know how to fix it. My code is below. Thanks in advance.

int main(void) 
{
int coin_count = 0;
float amount;

do 
{
    printf("How much change is owed (amount must be non-negative): \n"); 
    amount = get_float(); 
}
while(amount < 0);

int cent_amount = round(amount*100);

while(cent_amount>=0)
{
   if(cent_amount > 25)
   {
       cent_amount = cent_amount - 25;
       coin_count++;
   }
   else if(cent_amount > 10)
   {
       cent_amount = cent_amount - 10;
       coin_count++;
   }
   else if(cent_amount > 5)
   {
       cent_amount = cent_amount - 5;
       coin_count++;
   }
   else if(cent_amount > 1)
   {
       cent_amount = cent_amount - 1;
       coin_count++;
   }
}
printf("Minimum number of coins used: %i\n", coin_count);
}
1

Your while loop does not end up

EDIT:

(Thanks to SuperNovaCoder for your intervention) The problem is that equality must be achieved ie the conditions must be >=

EDIT1:

while(cent_amount>=0)

should be:

while(cent_amount>0)

To allow the loop to finish

| improve this answer | |
  • What do you mean? I used if/else statements in one while loop and it worked for me. Is there an issue I'm not seeing? – SuperNovaCoder Apr 26 '17 at 19:40
  • You're right, thanks for the clarification, the problem is in the sign > should be > = – MARS Apr 26 '17 at 20:05
  • I changed all of the > signs in my while loop to >= (and kept my do-while loop the same) but the problem persists... – ahl89 Apr 27 '17 at 16:40
  • No doubt should not be answered with haste, the condition of the second while is incorrect, if the condition of the second while is cent_amount> = 0 the loop never ends, since the amount returned will never reach negative values, The smallest value is zero, so the condition is always true, therefore we must Impose the while condition (cent_amount> 0) – MARS Apr 27 '17 at 20:12

You must log in to answer this question.

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