为什么我的 CS50 代码不工作,为什么我的代码总是溢出或给出 1 的值?

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

我正在研究 CS50 中的 "greedy" 算法。我不确定出了什么问题,但是当我输入一个值时它一直给我一个值 1 或溢出。

请看下面:

#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);
}

您正在 while 循环中初始化 "count" 值,因此每次循环运行时都会创建一个计数变量,该变量是该循环的本地变量。

当循环结束时,变量被销毁,这意味着您无法在 while 循环之外访问它。

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);
}