2015-02-09 59 views
-1
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便士。怎麼了?我的更換計算器有什麼問題?

+5

浮點運算是不精確解決大部分此類問題。將輸入金額轉換爲美分並使用整數。 – molbdnilo 2015-02-09 20:25:46

回答