2014-07-22 88 views
-2

下面,我將提供的代碼2個不同的模塊:Ruby:這兩個代碼塊有什麼區別?

代碼A座,而我知道有寫它的更好的方法,這就是我的思維過程,最初打算 代碼B座是一個更簡潔的方式的上述代碼

代碼塊答:

print "How much was your meal?" 
    meal_cost = Float(gets) 
    meal_cost = '%.2f' % meal_cost 

    print "What is the tax percentage in your state?" 
    tax_percent = Float(gets) 
    tax_percent = '%.2f' % tax_percent 

    tax_value = meal_cost.to_f * (tax_percent.to_f * 0.01) 
    tax_value = '%.2f' % tax_value 

    meal_with_tax = tax_value.to_i + meal_cost.to_i 
    meal_with_tax = '%.2f' % meal_with_tax 

    print "What percentage would you like to tip?" 
    tip_percent = Float(gets) 

    tip_value = (tip_percent.to_i * 0.01) * meal_with_tax.to_i 
    tip_value = '%.2f' % tip_value 

    total_cost = tip_value.to_i + meal_with_tax.to_i 
    total_cost = '%.2f' % total_cost 

    puts "The pre-tax cost of your meal was $#{meal_cost}." 
    puts "At #{tax_percent}%, tax for this meal is $#{tax_value}." 
    puts "For a #{tip_percent}% tip, you should leave $#{tip_value}." 
    puts "The grand total for this meal is then $#{total_cost}" 

代碼塊B:

puts "How much was your meal?" 
    meal_cost = Float(gets) 

    puts "Please enter your tax rate as a percentage (e.g., 12, 8.5)" 
    tax_percent = Float(gets) 

    puts "What percentage of your bill would you like to tip? (e.g., 15)" 
    tip_percent = Float(gets) 

    tax_value = meal_cost * tax_percent/100 
    meal_with_tax = meal_cost + tax_value 
    tip_value = meal_with_tax * tip_percent/100 
    total_cost = meal_with_tax + tip_value 

    print "The pre-tax cost of your meal was $%.2f.\n" % meal_cost 
    print "At %d%%, tax for this meal is $%.2f.\n" % [tax_percent, tax_value] 
    print "For a %d%% tip, you should leave $%.2f.\n" % [tip_percent, tip_value] 
    print "The grand total for this meal is then $%.2f.\n" % total_cost 

出於某種原因,在代碼A座,下面幾行:

meal_with_tax = tax_value.to_i + meal_cost.to_i 
    meal_with_tax = '%.2f' % meal_with_tax 

返回22,而不是22.4

有人可以幫助我瞭解爲什麼?

回答

1

to_i返回一個整數。

您可能需要使用to_f保持精度

value.round(1)可能是你正在尋找

1

當您在代碼塊a中使用.to_i將tax_value和meal_cost轉換爲整數時,您將失去精度。

0

to_i代表'to integer'。整數是一個沒有小數點的數字,因此在您撥打to_i之後,任何在小數點後面的數字都將被丟棄。

x = 22.123456 
y = 22.999999 
x == y   #=> false 
x.to_i == y.to_i #=> true 
+0

感謝您的解決方案!絕對忽略了這一點。 – jasonnoahchoi