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

罗马数字转整数代码异常:输入变更但输出始终相同求助

罗马数字转整数输出固定的问题解决

你的代码核心问题是函数内部使用了未定义的变量s,而非传入的参数RomanNum。如果之前的代码环境中恰好存在s变量,函数会一直复用这个旧值计算,导致输出固定;正常情况下运行还会直接抛出NameError。

修复后的代码:

RomanNum = input('Please Enter the Desired number in the form(e.g III):')
def romanToInt(RomanNum):
    # 罗马数字规则:大数在前则相加,小数在前则相减
    roman = { "I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000 }
    
    Int = 0
    
    for i in range(len(RomanNum)):
        if i+1 < len(RomanNum) and roman[RomanNum[i]] < roman[RomanNum[i+1]]:
            Int -= roman[RomanNum[i]]  
        else:
            Int += roman[RomanNum[i]]
    return Int

print(romanToInt(RomanNum))

关键修改说明:

将循环中所有的s替换为函数参数RomanNum,让函数真正使用用户输入的罗马数字进行计算,这样输出结果就会随输入变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:05:32