有人可以检查算法

问题描述:

该算法输入一个浮动值i,该值代表金额并返回支付该金额所需的最小硬币数量并返回整数c。有人可以检查算法

值C1 = 25,C 2 = 10,C 3 = 5,C4 = 1

我的代码工作完全所有用于输入除了当i = 4.2它应该返回18分的硬币,而其返回22枚硬币

i=i*100; 

while (i>0) { 
    if(i>=25) { 
     c = (int) i/25; 
     i= (int) i%25; 
    } 
    else if (i>=10 && i<25) { 
     c = c + (int) i/10; 
     i=(int) i%10; 
    } 

    else if(i>=5 && i<10) { 
     c = c + (int) i/5; 
     i = (int) i%5; 
    } 
    else if(i<5) { 
     c = c + (int) i/1; 
     i = (int) i%1; 
    } 
} 

printf("%d\n",c); 
+1

1.格式化代码,使其可读。 2.使用调试器 – 2014-09-03 20:13:19

+1

哇,居中?我认为GNU风格很难阅读。 – 2014-09-03 20:14:01

+0

如果需要考虑等值,例如:else if(i> = 10 && i NetVipeC 2014-09-03 20:19:58

你的问题是浮点精度。

float i = 4.2; 
i *= 100; 
printf("%f\n", i); 

打印:419.999969和不4.2因为它应该,在这种情况下419是导致22枚硬币的硬币的问题使用的值使用16 of 251 of 101 of 54 of 1 = total 22

使用:i = round(i * 100);而不是i = i * 100;

您需要考虑相等的值,例如:else if(i> = 10 & & i < 25),范围是[ini,fin),开始时关闭,结束时打开。如果您将else if更改为if,则不需要while loop

最终代码:

#include <stdio.h> 
#include <math.h> 

int main() { 
    int c = 0; 
    float iv = 4.2; 
    int i = round(iv * 100); 

    printf("%d\n", i); 
    if (i >= 25) { 
     c += i/25; 
     i = i % 25; 
    } 
    if (i >= 10) { 
     c += i/10; 
     i = i % 10; 
    } 
    if (i >= 5) { 
     c += i/5; 
     i = i % 5; 
    } 
    if (i > 0) { 
     c += i; 
    } 
    printf("%d\n", c); 

    return 0; 
} 

更多信息有关 What Every Programmer Should Know About Floating-Point Arithmetic