为什么我的CS50代码不起作用,为什么我的代码不断溢出或给出值1?

问题描述 投票:-2回答:1

我正在研究CS50中的“贪婪”算法。我不确定出什么问题,但是输入值时它总是给我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);
}
c cs50 greedy
1个回答
1
投票

您正在初始化while循环内的“ count”值,因此每次循环运行时,都会创建此循环本地的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);
}
© www.soinside.com 2019 - 2024. All rights reserved.