简体   繁体   中英

CS50 greedy algorithm

I just started C programming with cs50.

I tried to do the problem set about the greedy algorithm but can't seem to find the bug. My code is below.

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


int main (void)
{

int count = 0;

printf("how much is the change?: ");

float change = get_float();

while(change < 0)
{
   printf("change is to be more than 0");
   change = get_float();
 }

int amount = lroundf(change*100);

while(amount > 0)
{
  if ((amount-25) >= 25)
  {
      amount  =  amount - 25;
      count++;
  }

  else if ((amount-10) >= 10)
  {
      amount =  amount - 10;
      count++;
  }

  else if ((amount-5) >= 5)
  {
      amount = amount -5;
      count++;
  }

  else if((amount-1) >= 1)
  {
      amount = amount -1;
      count ++;
      break;
  }

  else
  {
   printf("you have no change \n");   
  }
  }
  printf("your number of coins is %i\n", count);

  }

When I input my change as 1, I am given back 8 coins. Can't seem to find where the bug is. Can anyone help me?

Firstly, you could try running your program with values for change that return simple answers, like 1 coin, using, for example, change = 0.25 . If that works, then you should start trying with some few coins, repeating one type, like you did with 1.00 , or joining a few types, like 0.06 . And after that, try big numbers and values with higher floating inaccuracy, like 4.10 . Following this should lead you to your answers.

If, after trying that, you still can't find the problem, then here is the answer: the problem is with the if / else if expressions. When you are trying to count the quarters, for example, the (amount-25) >= 25 doesn't work properly. You're trying to take away a quarter while amount is bigger or equal to 25, but your code just do that until it gets to less than 50. Developing your expression may help you see it: (amount-25) >= 25 -> (amount-25) + 25 >= 25 + 25 -> amount >= 50 .

Another problem you may find is with that break statement. It might get out from the loop earlier than expected. If you try running numbers like 0.04 and 0.03 you'll see the count stuck at 1 . After removing the first penny, the code breaks out of the loop leaving amount still bigger than 0. break s make it harder to see when the code is getting out of the loop and that's why many programmers recommend avoiding it whenever possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM