You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python硬币计算器程序:循环最终总价值实现求助

问题修复方案

你的代码核心问题是缩进错误,导致总价值的输出语句和后续的输入逻辑没有被正确包含在循环体内,另外还有字符串格式的小问题。修复后的完整代码如下:

def getCoin(coinType) :
    coinval = -1
    while coinval < 0:
        try:
            coinval = int(input(coinType))
            if coinval < 0:
                print("Coin counts cannot be negative. Please re-enter.")
        except ValueError:
            print("Illegal input. Value converted to zero")
            coinval = -1
    return coinval

print("welcome to the change calculator")
print()

choice = input("do you have change? (Y/N)")
# 校验初始输入合法性,避免非Y/N的无效输入
while choice.upper() not in ["Y", "N"]:
    print("Please enter Y or N.")
    choice = input("do you have change? (Y/N)")

while choice.upper() == "Y":
    print("Your choice was:", choice)

    hd = getCoin(" # Half-Dollars? ")
    q = getCoin(" # Quarters? ")
    d = getCoin(" # Dimes? ")
    n = getCoin(" # Nickels? ")
    p = getCoin(" # Pennies? ")
    
    totalvalue = (hd * 50) + (q * 25) + (d * 10) + (n * 5) + p
    dollars = totalvalue // 100  # 整数除法提取美元整数部分
    cents = totalvalue % 100     # 取余提取剩余美分部分
    
    # 修复字符串格式,让输出更通顺
    print(f"You have {totalvalue} cents.")
    print(f"This is {dollars} dollars and {cents} cents.")
    
    # 校验后续输入合法性
    choice = input("Do you have more change? (Y/N): ")
    while choice.upper() not in ["Y", "N"]:
        print("Please enter Y or N.")
        choice = input("Do you have more change? (Y/N): ")

print("Thanks for using the change calculator")

关键修复说明:

  • 缩进修正:将原本错位的输出语句和输入逻辑调整到while循环的正确层级,确保每次计算完硬币价值后,都能正常输出结果并询问是否继续操作。
  • 字符串格式优化:改用f-string简化输出代码,同时补充空格修正了"cents"前缺少空格的问题,让输出语句更符合阅读习惯。
  • 输入合法性增强:增加了对初始输入和后续输入的校验逻辑,避免用户输入非Y/N的内容导致程序逻辑异常。

内容的提问来源于stack exchange,提问作者Highnatzu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:18:33