我想创建一个程序,用户基本上“创建”一个购物清单,用户在其中输入商品和价格,直到他们想要退出。如果用户输入“q”或“Q”,那么程序应该停止提示用户,而是应该计算小计,加上名义上的 6% 销售税,并显示总结果。
我得到了第一部分,用户输入他们的项目和价格,但我不知道如何让它告诉我小计并给他们一张收据。我已经尝试了7个小时!!当我运行它时,它应该说:
Enter an item and its price, or ’Q/q’ to quit: eggs 2.13
Enter an item and its price, or ’Q/q’ to quit: milk 1.26
Enter an item and its price, or ’Q/q’ to quit: batteries 3.14
Enter an item and its price, or ’Q/q’ to quit: q
Receipt:
--------
eggs => $2.13
milk => $1.26
batteries => $3.14
---------
subtotal: $6.53
tax: $0.39
total: $6.92
这是我制作的代码:(有人可以帮我吗???)
def create_list
puts 'Please enter item and its price or type "quit" to exit'
items = gets.chomp.split(' ')
grocery_list = {}
index = 0
until index == items.length
grocery_list[items[index]] = 1
index += 1
end
grocery_list
end
def add_item (list)
items = ''
until items == 'quit'
puts "Enter a new item & amount, or type 'quit'."
items = gets.chomp
if items != 'quit'
new_item = items.split(' ')
if new_item.length > 2
#store int, delete, combine array, set to list w/ stored int
qty = new_item[-1]
new_item.delete_at(-1)
new_item.join(' ')
p new_item
end
list[new_item[0]] = new_item[-1]
else
break
end
end
list
end
add_item(create_list)
puts "Receipt: "
puts "------------"