Python甜点店代码报错:float无法转为整数的解决方法求助
解决'float' object cannot be interpreted as an integer错误及订单功能修复
错误原因拆解
- 变量名误用:
cake_cost函数里使用了base_diameter,但这个变量仅在customer_order中定义,函数自身的参数是diameter,属于未定义变量,需替换为传入的diameter参数。 - range参数类型不兼容:
range()要求起始/结束值必须是整数,但从customer_order传入的diameter是浮点型(比如输入2会被转成2.0),直接传入range会触发类型错误。 - 未定义变量:
cake_cost里的height_per_level没有定义,结合你的示例计算逻辑,应该使用传入的height参数。 - 功能不符合要求:
customer_order当前是返回金额,但作业要求是打印总金额,和你给出的示例输出不符。
修复后的完整代码
# 定义题目中提到的全局变量 CAKE_COST_PER_CM_CUBED = 4.0 SECRET_INGREDIENT = 19.99 # 补全get_pizza_area函数的示例实现(你应该已有该函数,此处为代码可运行补充) def get_pizza_area(diameter): import math radius = diameter / 2 return math.pi * radius ** 2 def cake_cost(diameter, height): ###returns cost as a float rounded total_area = 0 # 将浮点型diameter转为整数,满足range的参数要求 for i in range(1, int(diameter) + 1): total_area += get_pizza_area(i) # 使用传入的height替代未定义的height_per_level volume = total_area * height return round(volume * CAKE_COST_PER_CM_CUBED, 2) def customer_order(): ##ask for order and prints out cost cake_or_cookie = input("Would you like the cake or the cookie? ") diameter_input = input("What diameter? ") base_diameter = float(diameter_input) height_input = input("What height? ") height = float(height_input) s_ingredient = input("Do you want the secret ingredient? ") if cake_or_cookie.lower() == 'cake': base_cost = cake_cost(base_diameter, height) # 优化判断逻辑,兼容大小写输入 if s_ingredient.lower() in ["yes", "y"]: total_cost = round(base_cost + SECRET_INGREDIENT, 2) else: total_cost = base_cost # 按照示例格式打印总金额 print(f"The cost is ${total_cost}") else: print("ew, get out of my store.") # 测试调用 customer_order()
关键修改说明
- 把
cake_cost里的base_diameter替换为参数diameter,并通过int(diameter)将浮点型转为整数,解决range的类型错误。 - 用传入的
height参数替代未定义的height_per_level,修复变量未定义问题。 - 修改
customer_order的逻辑,将return改为print语句,匹配示例输出格式;同时优化秘密配料的判断逻辑,避免大小写敏感问题。
测试验证
运行customer_order()后,输入示例内容:
Would you like the cake or the cookie? cake What diameter? 2 What height? 1 Do you want the secret ingredient? yes
会输出:The cost is $35.7,和预期一致。
内容的提问来源于stack exchange,提问作者Iplaysoccer
相关产品推荐
相关产品推荐

