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

Python代码求助:如何获取三个输入数字的中间值?

解决三个数的中间值计算问题

Got it, let's fix this up for you! Your code already does a great job collecting the three numbers and grabbing the min/max—you just need a simple way to get that middle value. Here are a couple of straightforward approaches:

方法1:用总和减去最大值和最小值

因为三个数的总和等于「最小值 + 中间值 + 最大值」,反过来推导,中间值就是总和减去另外两个值。这种方法简单直接,专门适配三个数的场景:

new_list = []
for i in range(3):
    new_list.append(int(input("Enter a number: ")))
min_val = min(new_list)
max_val = max(new_list)
middle_val = sum(new_list) - min_val - max_val
print("The max is %d, the middle is %d and the min is %d." % (max_val, middle_val, min_val))

方法2:排序后取中间元素

如果以后需要处理更多数字,排序的方法扩展性更好。对列表排序后,三个元素的中间值就是索引为1的元素(Python列表索引从0开始):

new_list = []
for i in range(3):
    new_list.append(int(input("Enter a number: ")))
sorted_nums = sorted(new_list)
min_val = sorted_nums[0]
middle_val = sorted_nums[1]
max_val = sorted_nums[2]
print("The max is %d, the middle is %d and the min is %d." % (max_val, middle_val, min_val))

小提醒

你原来的代码里把print()的结果赋值给z是不对的——print()函数只会输出内容到控制台,它的返回值是None,所以永远拿不到中间值哦。上面的两种方法都能完美解决这个问题,选哪种都可以~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:43:42