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

Python中min函数仅读取首数字问题求助:需支持两位数取最小值

问题解决:正确比较数字大小获取最小值

你的问题核心在于**input()函数默认返回字符串类型**,直接用min()比较字符串时,是按字符的ASCII码顺序进行对比(比如"10"会被判定为比"2"小,因为"1"的ASCII码值小于"2"),而非数字的实际大小。

修正方法很简单,只需把每个输入的字符串转换成数字类型(整数用int,小数用float),再调用min()即可:

c = int(input("Enter a number: "))
b = int(input("Enter a number: "))
a = int(input("Enter a number: "))
d = min(c, b, a)
print("Smallest: " + str(d))
# 用f-string输出更简洁:print(f"Smallest: {d}")

如果需要支持小数输入,把int替换成float即可:

c = float(input("Enter a number: "))
b = float(input("Enter a number: "))
a = float(input("Enter a number: "))
d = min(c, b, a)
print(f"Smallest: {d}")

如果要处理更多数量的输入,还可以用循环收集输入值,再取最小值,写法更灵活:

numbers = []
for _ in range(3):
    num = float(input("Enter a number: "))
    numbers.append(num)
smallest = min(numbers)
print(f"Smallest: {smallest}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:54:54