我在Lua和C中编写了这个程序,这是一个greedy algorithm。
Greedy = function(num)
local q = 0;
local d = 0;
local n = 0;
local p = 0;
local x = 1;
while x == 1 do
if (num >= 0.25) then
q = q + 1;
num = num - 0.25;
print("q");
elseif (num >= 0.10) then
d = d + 1;
num = num - 0.10;
print("d");
elseif (num >= 0.05) then
n = n + 1;
num = num - 0.05;
print("n");
elseif (num >= 0.01) then
p = p + 1;
num = num - 0.01;
print("p");
end
if (num == 0) then
x = 0;
end
end
if (x == 0) then
local all = q+d+n+p;
print(all);
end
end
Greedy(1);
此代码适用于某些数字,但如果我尝试计算0.90,0.04或0.12之类的数字,它将无法工作,我也有相同的代码用C编写。但是我有同样的问题。
#include <stdio.h>
int greedy(void){
int quarter = 0;
int dime = 0;
int nickel = 0;
int penny = 0;
float num = 0.40;
int x = 1;
while(x == 1){
if (num >= 0.25){
quarter = quarter + 1;
num = num - 0.25;
printf("q\n");
}else if(num >= 0.10){
dime = dime + 1;
num = num - 0.10;
printf("d\n");
}else if(num >= 0.05){
nickel = nickel + 1;
num = num - 0.05;
printf("n\n");
}else if(num >= 0.01){
penny = penny + 1;
num = num - 0.01;
printf("p\n");
};
if(num == 0){
x = 0;
};
};
if(x == 0){
int all = quarter + dime + nickel + penny;
printf("%i\n", all);
};
return 0;
};
int main(void){
greedy();
}
我做错了什么?
答案 0 :(得分:2)
问题在于,许多浮点数无法准确表示(使用double
或float
),请在Lua中尝试:
> print(0.9 == 0.9 - 0.2 + 0.1 + 0.1)
false
它在数学上应该相等,但不是在这里。 C代码也一样。
答案 1 :(得分:1)
看到你的范围正在计算你的钱,用这种方式重写你的代码:
Greedy = function(num)
local q = 0;
local d = 0;
local n = 0;
local p = 0;
local x = 1;
num=num*100
while x == 1 do
if (num >= 25) then
q = q + 1;
num = num - 25;
print("q");
elseif (num >= 10) then
d = d + 1;
num = num - 10;
print("d");
elseif (num >= 5) then
n = n + 1;
num = num - 5;
print("n");
elseif (num >= 1) then
p = p + 1;
num = num - 1;
print("p");
end
if (num == 0) then
x = 0;
end
end
if (x == 0) then
local all = q+d+n+p;
print(all);
end
end
Greedy(1);