我一生都无法弄清楚为什么 my:generate_receipt
方法54.9
在我的“进口餐盘项目”应该等于时返回54.65
。我编写了 RSpec 测试来确认数组确实返回了正确的值。
47.50 + 4.75 + 2.40 = 54.65
为什么它返回54.9
而不是返回54.65
?!这种围捕发生在哪里?如何让它返回正确的值?我难住了。
describe :calcualte_sales_tax do
it "should return the correct array" do
calculate_sales_tax(@receipt).should eq([0, 4.75])
end
end
describe :calculate_import_tax do
it "should return the correct array" do
calculate_import_tax(@receipt).should eq([0.50, 2.40])
end
end
@receipt = {
"1"=>{:item=>"imported chocolates", :price=>10.00, :quantity=>1},
"2"=>{:item=>"imported dinner plates", :price=>47.50, :quantity=>1}
}
def generate_receipt(receipt)
n = 0
while n < receipt.length
receipt["#{n+1}"][:price]+=calculate_sales_tax(receipt)[n]
receipt["#{n+1}"][:price]+=calculate_import_tax(receipt)[n]
n+=1
end
receipt
end
def calculate_import_tax(receipt)
taxes = []
receipt.each do |k,v|
if (v[:item] =~ /imported/)
subtotal = v[:price]
# v[:price]+=(((((5 * subtotal)/100)*20.ceil) / 20.0))
# taxes<<(5 * subtotal)/100
taxes<<((5 * subtotal/100)*20).ceil/20.0.round(2)
else
taxes<<0
end
end
taxes
end
def calculate_sales_tax(receipt)
tax_free_items = ["book", "chocolate bar", "chocolates", "pills"]
taxes = []
receipt.each do |k,v|
if (v[:item] =~ /chocolate\s/) ||
(v[:item] =~ /chocolates/) ||
(v[:item] =~ /book/) ||
(v[:item] =~ /pills/)
taxes<<0
else
subtotal = v[:price]
# v[:price]+=(((((10 * subtotal)/100)*20.ceil) / 20.0))
# taxes<<(10 * subtotal)/100
taxes<<((10 * subtotal/100)*20).ceil/20.0
end
end
taxes
end