我在编程方面有101%的菜鸟,而且我已经注册了CS50。我试图充分利用它,所以我总是采取不太舒服的挑战,以便尽量学习。
我已经完成了CS50&pset1中贪婪挑战的代码。为了让它变得那么好,干净和简单,我已经眯着大脑,因为我的谦虚知识允许我这样做,但每次检查代码时我都会收到一个错误提示。
特此我附上代码检查和我的代码:
CS50终端脚本检查代码:
:) greedy.c exists
:) greedy.c compiles
:) input of 0.41 yields output of 4
:) input of 0.01 yields output of 1
:) input of 0.15 yields output of 2
:) input of 1.6 yields output of 7
:( input of 23 yields output of 92
\ expected output, but not "94\n"
:) input of 4.2 yields output of 18
:) rejects a negative input like -.1
:) rejects a non-numeric input of "foo"
:) rejects a non-numeric input of ""
这是我的代码:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
float change;
int coins = 0;
int quantity;
int main (void)
{
do
{
printf("O hai! How much change is owed?\n");
change = get_float();
}
while (change < 0);
//converting float change (dollars) into integer change (cents)
quantity = round(change * 100.00);
while (quantity > 25) //This runs as long as quantity left is bigger than a quarter coin
{
quantity -= 25;
coins++;
}
while (quantity >= 10) //This runs as long as quantity left is bigger than a dime coin
{
quantity -= 10;
coins++;
}
while (quantity >= 5) //This runs as long as quantity left is bigger than a nickel coin
{
quantity -= 5;
coins++;
}
while (quantity >= 1) //This runs as long as quantity left is bigger than 0
{
quantity -= 1;
coins++;
}
printf("%i\n", coins);
}`
免责声明:我想指出,我完全了解哈佛的“诚实守则”。我并没有试图找到问题的简单解决方案,只是摆脱了这个挑战。
我希望有人能够利用自己的时间写下一个能够启发我的解释并帮助我理解代码失败的为什么。 我没有寻求任何答案,如果你不是这样的话,你也不必指出它。 我只是一个没有经验的CS初学者,他愿意阅读你所有的答案,最后明白为什么那些应该工作的东西根本不起作用。
非常感谢您的耐心和时间!
答案 0 :(得分:1)
问题在于您的第一次比较,即(quantity > 25)
。如果您的总金额为23美元,则需要23 * 4 = 92 coins
。
但是,如果你减去了那些季度中的91个,那么你最终会得到(quantity == 25)
并且检查失败(因为quantity
不再严格地大于而不是{{1但是等于它),将你推入2角钱,然后进入最后的镍币,使其成为显示的94枚硬币。
修复是(您现在应该已经猜到)用25
答案 1 :(得分:0)
#include <stdio.h>
#include <cs50.h>
#include <math.h>
float change; // change can be float
int amount;
int coins = 0;
int main(void)
{
do
{
change = get_float ("Change owed: ");
}
while(change < 0);
amount = round(change * 100);
while( amount >= 25)
{
amount -= 25;//This is the end of loop substract until it reaches to the
//25 or less
coins ++;// this is the count of coins that how many owned coins will
//become big bite
}
while(amount >= 10)
{
amount -= 10;
coins ++;
}
while(amount >= 5)
{
amount-=5;
coins++;
}
while(amount >= 1)
{
amount -= 1;
coins++;
}
printf("The minimum number of coins that is to be used is: %i",coins);//the minimum number of coins
printf(" coins.");
printf("\n");
}