CS50 pset1贪心不起作用

时间:2016-07-06 07:27:31

标签: c cs50

和其他人一样,我正在尝试制作一个名为“贪婪”的程序,它会告诉我最少量的硬币,我必须给某人作为给定金额的变化。我做了这个,但它给了我错误数量的硬币,我不知道为什么:(

 #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,但它应该告诉我我必须给他one coin... a quarter

2 个答案:

答案 0 :(得分:0)

您的前2个循环不会处理价值-O25

实际上,您的算法为您提供了7,即10 2 coins10 cent 5 coins

你必须检查它们,所以:

1 cent

答案 1 :(得分:0)

这是我的代码:

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