2017-09-25 60 views
0

這是我的測試輸出:爲什麼我的程序在某些測試中正常工作,而不是爲其他人測試?

:) greedy exists 

:) greedy compiles 

:(input of 0.41 yields output of 4 
    expected "4\n", not "3\n" 

:(input of 0.01 yields output of 1 
    expected "1\n", not "0\n" 

:) input of 0.15 yields output of 2 

:) input of 1.6 yields output of 7 

:) input of 23 yields output of 92 

:) 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> 

void count_coins(); 

int coin = 0; 
float change = 0; 

int main(void) 
{ 
    do 
    { 
    change = get_float("How much change is owed? "); 
    } 
    while (change < 0); 

    count_coins(); 

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

void count_coins() 
{ 
    while (change > 0.24) 
    { 
     coin++; 
     change -= 0.25; 
     // printf("%.2f\n", change); 
    } 

    while (change > 0.09) 
    { 
     coin++; 
     change -= 0.10; 
     // printf("%.2f\n", change); 
    } 

    while(change > 0.04) 
    { 
     coin++; 
     change -= 0.05; 
     // printf("%.2f\n", change); 
    } 

    while (change >= 0.01) 
    { 
     coin++; 
     change -= 0.01; 
     // printf("%.2f\n", change); 
    } 
} 
+1

什麼是應該發生的?你採取了哪些調試步驟? –

+3

也許你假設'浮動'可以保存你試圖存儲的確切數字,但它不能。數字可能會在這裏和那裏近似,以適應「浮動」如何工作的規範。你所做的比較很可能會導致怪異的行爲。你應該在那裏使用整數,用'100'來表示'1.00'等。 – Havenard

+0

@DaveNewton該程序假設計算需要給出的最小數量的硬幣作爲改變。我注意到問題是當我們到達時(改變> 0.01) –

回答

0

由於Havenard已經寫了,問題是,change被存儲爲float。 對於這樣的程序,change必須存儲爲整數值。

這是你與int,而不是float代碼:

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

void count_coins (void); 

int coin = 0; 
int change = 0; 

int main (void) { 
    do { 
     change = 41; // insert a get integer function here 
    } while (change < 0); 

    count_coins(); 

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

void count_coins (void) { 
    while (change >= 25) { 
     coin++; 
     change -= 25; 
    } 

    while (change >= 10) { 
     coin++; 
     change -= 10; 
    } 

    while(change >= 5) { 
     coin++; 
     change -= 5; 
    } 

    while (change >= 1) { 
     coin++; 
     change -= 1; 
    } 
} 
+1

這就像是通過反覆減法來劃分,並且可能需要很長時間才能執行大量的總和。你知道'%'模數aka餘數運算符嗎? –

+0

@WeatherVane是的,我知道這一點。我的意圖是改變數據類型,同時保持其餘的邏輯完全相同,以便OP能夠看到他的程序失敗的地方。 –

相關問題