2017-02-15 99 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