Ruby:这两个代码块之间有什么区别?

时间:2014-07-22 03:39:52

标签: ruby

下面,我将提供2个不同的代码块:

代码块A,虽然我知道有更好的写作方式,但我的思维过程最初是在哪里 代码块B是上述代码的简洁方法

代码块A:

    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

有人可以帮助我理解为什么吗?

3 个答案:

答案 0 :(得分:1)

当您将tax_value和meal_cost转换为代码块中带有.to_i的整数时,您将失去精确度。

答案 1 :(得分:1)

to_i 会返回一个整数。

您可能希望使用 to_f 来维持精确度

value.round(1)可能是您正在寻找的解决方案

答案 2 :(得分:0)

to_i代表'到整数'。整数是一个没有小数点的数字,因此在调用to_i后,deciaml点之后的任何内容都将被丢弃。

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