2016-09-03 32 views
-3

我的貪婪程序的代碼對於目前爲止所有的數字都適用,除了4.2以外。 會很感激,如果任何人都可以指出錯誤cs50 pset1貪婪異常錯誤

:) 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 
**:(input of 4.2 yields output of 18 
    \ expected output, but not "22\n"** 
:) 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> 

int main(void) 
{ 
    float x; 
    do 
{ 
    printf("how much change is owed(in dollars)?:\n"); 
    x = GetFloat(); 
} 
    while (x < 0); 


    x = x*100; 
    int i = 0; 
while (x >= 25) 
{ 
    x = (x-25); 
    i++; 
} 


    while (x >= 10) 
{ 
    x = (x-10); 
    i++; 
} 

while (x >= 5) 
{ 
    x = (x-5); 
    i++; 
} 

while (x >= 1) 
{ 
    x = (x-1); 
    i++; 
} 
printf("%d\n",i); 
} 
+4

請參閱[浮點運算是否被破壞?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken)。更好的是,使用int值。 SO上有很多「變化」的問題展示了這個問題。從「不尋常」到目前爲止,這是你經歷的一個階段。 –

+0

如果您需要精確值,請不要使用浮點數。 – Olaf

回答

0

更改以下行

x = x*100;

x = floor(x*100); printf("rounded value: %f\n", x);

它將打印rounded value: 419併爲此22是正確的答案。 (16x25 + 1x10 + 1x5 + 4x1)

這就是現在發生的情況,因爲存儲在x中的值接近420,但略小一些。

0

此錯誤已做的浮點不精確,運行下面的代碼,你看看有什麼引擎蓋下真正發生的事情:

float x = 4.2; 
printf("%.50f\n", x); 

所以不是最好先將值轉換爲相應的正整數到美分的全部價值(請記住,4.2美元與420美分相同),並用此值進行計算(並且不要忘記先將值舍入)。

0

浮點數總是存在不精確性。因此建議我們將float轉換爲int。您可以通過 int amount = lroundf(change*100);這樣做也注意,該值乘以100倍。這是擺脫美分,然後使用'lroundf'命令四捨五入這些不需要的值。