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

编写DMOJ CCC '06 J1代码时,函数返回值却得到NoneType的问题

解决CCC '06 J1卡路里计算的代码问题

问题根源

你的代码存在三个核心问题:

  1. return print(...)的错误用法:print()函数本身返回None,所以你的函数最终返回的是None,而非卡路里数值——这就是你遇到NoneType错误的原因。
  2. 多余的循环逻辑:每个函数里的for循环完全没必要,输入的数字(如brg)直接对应列表索引(减1后),不需要遍历。
  3. 未完成核心需求:代码没有将四个餐品的卡路里相加得到总数值,而这正是CCC '06 J1的要求。

修正后的简洁代码

直接用列表存储卡路里,通过输入值减1获取对应索引,计算总和即可:

# 列表索引0对应选项1,索引3对应选项4,直接存储卡路里数值
burgers = [461, 431, 420, 0]
drinks = [130, 160, 118, 0]
sides = [100, 57, 70, 0]
desserts = [167, 266, 75, 0]

# 获取输入并转换为列表索引
brg_idx = int(input()) - 1
side_idx = int(input()) - 1
drink_idx = int(input()) - 1
dessert_idx = int(input()) - 1

# 计算总卡路里并输出
total_cal = burgers[brg_idx] + drinks[drink_idx] + sides[side_idx] + desserts[dessert_idx]
print(f"Total calories: {total_cal}")

保留函数写法的修正版

如果坚持用函数实现,让函数返回数值而非print的结果:

b = [["1", 461], ["2", 431], ["3", 420], ["4", 0]]
dr = [["1", 130], ["2", 160], ["3", 118], ["4", 0]]
s = [["1", 100], ["2", 57], ["3", 70], ["4", 0]]
de = [["1", 167], ["2", 266], ["3", 75], ["4", 0]]

brg = int(input())
sord = int(input())
drk = int(input())
dess = int(input())

def get_burger_cal():
    return b[brg-1][1]

def get_side_cal():
    return s[sord-1][1]

def get_drink_cal():
    return dr[drk-1][1]

def get_dessert_cal():
    return de[dess-1][1]

# 计算总和并打印
total = get_burger_cal() + get_side_cal() + get_drink_cal() + get_dessert_cal()
print(f"Total calories: {total}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:54:17