CS50 pset1 贪心不工作

CS50 pset1 Greedy not working

和这里的其他人一样,我正在尝试制作一个名为 greedy 的程序,它会告诉我在给定金额的情况下我必须给某人找零的最少硬币数量。我做了这个,但它给了我错误数量的硬币,我不知道为什么 :(

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

 int main(void)

 {
     float given_amount;
     int cent_count;
     int coin_count = 0; 

     do
     {
        printf("What is the amount of change I owe you?\n");
        given_amount = GetFloat();
     }
     while (given_amount < 0);

     cent_count = (int)round(given_amount * 100);

     while (cent_count > 25)
     {
         coin_count++;
         cent_count -= 25;
     }
     while (cent_count > 10)
     {
         coin_count++;
         cent_count -= 10;
     }
     while (cent_count >= 1)
     {
         coin_count++;
         cent_count -= 1;
     }

     printf("Take these %d coins\n", coin_count);

 }

如果我告诉程序我需要回馈 25 cents 程序告诉我我必须回馈那个人 7 coins,但它应该只是告诉我我必须回馈他 [=13] =].

您的前 2 个循环不处理值 2510

实际上您的算法给您 7,即:10 cent2 coins,以及 1 cent5 coins

你必须检查它们,所以:

 while (cent_count >= 25)
 {
     coin_count++;
     cent_count -= 25;
 }
 while (cent_count >= 10)
 {
     coin_count++;
     cent_count -= 10;
 }

这是我的代码:

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

int main(void)
{
float input = -1.00;
int n = 0;
int c = 0;

printf("O hai! How much change is owed?: ");
do
{
input = GetFloat();
if(input < 0)
printf("Positive number, please!: ");
}
while (input < 0);
c = roundf(input * 100);

while(c >= 25)
{ 
    c = c - 25;
    n++;
}
while (c >= 10)
{
    c = c - 10;
    n++;
}
while (c >= 5)
{
    c = c - 5;
    n++;
}
n = n + c;

printf("%i\n", n);
}