print ('please enter a roman numeral')
romannum = input()
lenrm = len(romannum)
total = 0
for i in range (lenrm):
numone = 0
numtwo = 0
if (romannum[i]).lower() == 'i':
numone = numone + 1
if (romannum[i]).lower() == 'v':
numone = numone + 5
if (romannum[i]).lower() == 'x':
numone = numone + 10
if (romannum[i + 1]).lower() == 'i':
numtwo = numtwo + 1
if (romannum[i + 1]).lower() == 'v':
numtwo = numtwo + 5
if (romannum[i + 1]).lower() == 'x':
numtwo = numtwo + 10
if numone < numtwo:
total = total + (numtwo - numone)
else:
total = total + numone
i += 1
print (total)
输入xiv
,我得到一条错误消息
Traceback (most recent call last):
File "C:\Users\poona\Python\roman_numeral_reader.py", line 18, in <module>
if (romannum[i + 1]).lower() == 'i':
IndexError: string index out of range
所以你有一个长度为5的输入,比如说IIIII,现在你取范围(5),这意味着它将迭代的最高值是4(从0到4,包括这两个),现在索引4是你的5索引长数值中的最后一个索引,因为我们从0开始计算索引,所以当你加上1,你得到的索引5超出了范围。你知道吗
对你来说
你的问题是错误
string index out of range
表示您正试图访问字符索引 不在字符串长度的范围内。 字符串基于0,因此第一个字符位于索引0处。你知道吗使用
romannum[i + 1]
时,您需要确保i + 1
不大于存储的字符串的长度 在名为romannum
的变量中减去1,因为它是基于0的。你知道吗罗马数字往往与求和相反 i、 e.
I
之前的V
被解释为4,因为I
小于V
并在V
之前。你知道吗因此,如果字符串被反转,则将每个字符改为 十进制等价,然后与上次存储的十进制进行比较 值,以确定是否要添加或减去当前十进制数。你知道吗
这看起来很简单,您试图访问
xiv
中v
旁边的字符,当然,这是越界的。你知道吗我建议在确定下一个字符之前检查边界:
相关问题 更多 >
编程相关推荐