puts "Welcome to the change calculator. Give me a dollar value, and I will give you the least number of coins equal to that amount."
dollar = gets.to_f
quarters = dollar / 0.25
remains1 = dollar % 0.25
dimes = remains1 / 0.10
remains2 = remains1 % 0.10
nickels = remains2 / 0.05
remains3 = remains2 % 0.05
pennies = remains3 / 0.01
puts "Your change is #{quarters.to_i} Quarters, #{dimes.to_i} Dimes, #{nickels.to_i} Nickels, and #{pennies.to_i} Pennies."
它应该给出硬币的变化,但是舍入有问题。例如,当我输入2.32美元时,它输出"您的更改是9个季度,0个维度,1个镍币和1个便士。"它应该是2便士。怎么了?
答案 0 :(得分:0)
浮点数不能精确地表示所有实数,并且浮点运算不能精确地表示真正的算术运算,这会导致许多令人惊讶的情况。
我建议阅读:https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
您可以使用BigDecimal
代替浮点数
require 'bigdecimal'
#...
dollar = BigDecimal.new(gets)
#...