2017-09-25 84 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能够看到他的程序失败的地方。 –

相关问题