2016-09-03 31 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'命令四舍五入这些不需要的值。