这是一个 Python 编程课程的练习题,要求编写一个硬币找零游戏程序。游戏规则是用户需要输入一定数量的 5 美分、10 美分、20 美分、50 美分、1 美元和 2 美元硬币,总金额恰好等于 2 美元。如果用户成功,则程序显示祝贺信息;否则,程序显示失败信息以及总金额与 2 美元的差额。
解决方案:
为了解决这个问题,可以将程序分为多个函数,每个函数负责不同的任务。首先,我们需要定义一些全局变量来存储硬币的面值和用户输入的数量。然后,在主函数中,我们可以通过调用其他函数来完成以下步骤:
- 显示游戏规则
- 从用户输入硬币的数量
- 显示用户输入的硬币数量
- 计算总金额
- 判断总金额是否等于 2 美元
- 显示祝贺信息或失败信息
# 全局变量
v_five = float(0.05)
v_ten = float(0.10)
v_twenty = float(0.20)
v_fifty = float(0.50)
v_one_dollar = int(1)
v_two_dollar = int(2)
dollar = 0
def main():
"""主函数"""
intro() # 显示游戏规则
# 从用户输入硬币的数量
five = float(input(" Enter number of FIVE CENT coins: "))
ten = float(input(" Enter number of TEN CENT coins: "))
twenty = float(input(" Enter number of TWNETY CENT coins: "))
fifty = float(input(" Enter the number of FIFTY CENT coins: "))
one_dollar = int(input(" Enter the number of ONE DOLLAR coins: "))
two_dollar = int(input(" Enter the number of TWO DOLLAR coins: "))
# 显示用户输入的硬币数量
show_change(five, ten, twenty, fifty, one_dollar, two_dollar)
# 计算总金额
calculate_value(five, ten, twenty, fifty, one_dollar, two_dollar)
# 判断总金额是否等于 2 美元
if dollar == 2.00:
print(" \n Congratulations! You've hit a perfect 2!")
print("")
else:
if dollar < 2.00:
print(" \n Oops! You were a little under 2!")
print("")
print(" Your total was: ", dollar)
else:
print(" \n Oh no! You went over 2!")
print("")
print(" Your total was: ", dollar)
def intro():
"""显示游戏规则"""
print("")
print(" Welcome to the Coin Change game!")
print(" Enter a number for each denomination below")
print(" Your total should be $2 and no more.")
print(" Good Luck!\n")
def show_change(five, ten, twenty, fifty, one_dollar, two_dollar):
"""显示用户输入的硬币数量"""
print("")
print(" You entered: \n\n {} five cent(s) \n {} ten cent(s) \n {} twenty cent(s) \n {} fifty cent(s) \n {} one dollar \n {} two dollar coins".format(five, ten, twenty, fifty, one_dollar, two_dollar))
def calculate_value(five, ten, twenty, fifty, one_dollar, two_dollar):
"""计算总金额"""
fiveAmount = v_five * five
tenAmount = v_ten * ten
twentyAmount = v_twenty * twenty
fiftyAmount = v_fifty * fifty
oneAmount = v_one_dollar * one_dollar
twoAmount = v_two_dollar * two_dollar
global dollar
dollar = fiveAmount + tenAmount + twentyAmount + fiftyAmount + oneAmount + twoAmount
if __name__ == "__main__":
main()
代码例子:
上面的代码是一个完整的 Python 程序,可以实现硬币找零游戏。用户只需要按照提示输入硬币的数量,程序就会自动计算总金额并判断是否等于 2 美元。如果用户成功,程序会显示祝贺信息;否则,程序会显示失败信息以及总金额与 2 美元的差额。
注意,在上面的代码中,我们使用了一个名为 __name__
的特殊变量。这个变量的值是 "__main__"
,表示正在执行当前脚本。这是为了确保 main()
函数只在程序的主模块中被调用,而不会在其他模块中被调用。