此算法输入一个表示金额的浮动值i
,返回支付该金额所需的最小硬币数,并返回一个整数c。
值c1=25,c2=10,c3=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("%dn",c);
问题在于浮点精度。
float i = 4.2;
i *= 100;
printf("%fn", i);
打印:419.999969
而不是4.2
,在这种情况下,419
是硬币问题中使用的值,导致22枚硬币使用16 of 25
、1 of 10
、1 of 5
和4 of 1
=total 22
使用:i = round(i * 100);
而不是i = i * 100;
您需要考虑相等的值,例如:否则,如果(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("%dn", 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("%dn", c);
return 0;
}
有关的更多信息每个程序员应该知道的关于浮点算术的知识