2017-02-15 102 views
0

我在这里问这个愚蠢的问题有点惭愧,但事实是,我已经尝试了一切,但仍然看不到错误在哪里。CS50 pset1贪婪的挑战

关于编程,我是101%的noob,并且我参加了CS50。我试图从中获得最大收益,所以我总是采取不那么舒适的挑战,以尝试和学习最多。

我已经在CS50的pset1中完成了贪婪挑战的代码。为了让它像我的卑微的知识一样好,干净和简单,我已经彻底弄清了自己的想法,但每次检查我的代码时,我都会收到提示,只是出现一个错误。

在此我附上两个,代码检查,我wirtten代码:

经过代码由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

'量> 25'更换检查 - >'量> = 25' – BLUEPIXY

+0

你什么输出为0.25? –

+0

1!现在解决了!非常感谢你! – Togeri

回答

1

问题出在您第一次比较时,读取(quantity > 25)。当你有23美元的总和时,你期望23 * 4 = 92 coins

但是,当你已经减去那些你最终4分之(quantity == 25)的91和校验失败(因为quantity不再严格大于25但等于它),通过推你到2次助攻和然后进入最后的镍,使其显示94硬币。

解决方法是(你现在应该已经猜到了吧)与(quantity >= 25)

+1

哦,我明白了!非常感谢你@YePhIcK! 我明白问题所在。非常轻轻地解释!对此,我真的非常感激! – Togeri