Search code examples
ccs50greedy

Why is my CS50 code not working and why my code keeps overflowing or giving a value of 1?


I am working on the "greedy" algo in CS50. I am not sure what's wrong but it keeps giving me a value of 1 or overflowing when I input a value.

Please see below:

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

int main(void)
{
     //define variables
     float change;
     do
     {
         change=get_float("change: ");
     }
      while(change<= 0);
     // change float to integer define variable

     int amount = round (change*100);
     // define the possible coins with each situation
      int a1,b,c,d;
      a1=amount/25;
      b=(amount-a1*25)/10;
      c=(amount-a1*25-b*10)/5;
      d=(amount-a1*25-b*10-c*5)/1;
    //

     while (amount>=25)
     {
         int a1_count++;
     }
     while (amount>10&&amount<25)
     {
         int b_count++;
     }
     while (amount>5&&amount<10)
      {
         int c_count++;
      }
      while ( amount>1&& amount<5)
      {
         int d_count++;
      }
      // total of the coins been used 
      int coins= a1_count+b_count+c_count+d_count;
      printf("number of coins given: %i\n",coins);
}

Solution

  • You are initializing your "count" values inside your while loops, so each time the loop runs it create a count variable that is local to this loop.

    When the loop ends the variable is destroyed, meaning you can't access it outside the while loop.

    int main(void)
    {
         //define variables
         float change;
         do
         {
             change=get_float("change: ");
         }
          while(change<= 0);
         // change float to integer define variable
    
         int amount = round (change*100);
         // define the possible coins with each situation
          int a1,b,c,d;
          a1=amount/25;
          b=(amount-a1*25)/10;
          c=(amount-a1*25-b*10)/5;
          d=(amount-a1*25-b*10-c*5)/1;
        //
        int a1_count = 0, b_count = 0, c_count = 0, d_count = 0;
        while (amount>=25)
        {
            a1_count++;
            amount -= 25;
        } 
        while (amount>10&&amount<25)
        {
            b_count++;
            amount -= 10;
        } 
        while (amount>5&&amount<10)
        {
            c_count++;
            amount -= 5;
        } 
          while ( amount>1&& amount<5)
          {
            d_count++;
            amount -= 1;
          }
          // total of the coins been used 
          int coins= a1_count+b_count+c_count+d_count;
          printf("number of coins given: %i\n",coins);
    }