I am working on the below problem:
Write a method to calculate change from a vending machine. Please refer to the actual note and coin in Australia, and each can drink cost $1.6.
Sample Input:
Please enter note or coin (0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10 or 20): 1
Please enter note or coin (0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10 or 20): 1
- Coca Cola
- Sprite
- Fanta
Select drink: 2
Sample Output:
$10 note: 0
$5 note: 0
$2 coin: 0
$1 coin: 0
50c coin: 0
20c coin: 2
10c coin: 0
5c coin: 0
I can’t figure out how to write the code to display the change correctly, I’ve spent ages googling and I still can’t figure it out!!
def vending_machine
drinks = ["Coca Cola", "Sprite", "Fanta"]
cost = 1.60
payment = 0
puts "Cost per drink = $#{cost}"
while payment < cost
print "Please enter note or coin (0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10 or 20): "
payment = gets.chomp.to_i
end
puts "Make your selection:\n1. Coca Cola\n2. Sprite\n3. Fanta"
selection = gets.chomp.to_i
case selection
when 1
puts "Your #{drinks[0]} has been dispensed."
when 2
puts "Your #{drinks[1]} has been dispensed."
else
puts "Your #{drinks[2]} has been dispensed."
end
if payment > cost
change = payment - cost
puts "Your change is #{change.to_f}"
puts " $10 note: #{change.to_i / 10}
$5 note: #{change.to_i / 5}
$2 coin: #{change.to_i / 2}
$1 coin: #{change.to_i / 1}
50c coin: #{change.to_i / 0.50}
20c coin: #{change.to_i / 0.20}
10c coin: #{change.to_i / 0.10}
5c coin: #{change.to_i / 0.05}"
else
puts "Have a great day!"
end
end