“ IndexError:字符串索引超出范围”

时间:2019-08-02 01:34:35

标签: python-3.x

我正在尝试编写一个简单的程序,告诉您e的多少位数(来自数学)等于您的近似值...如果有一个或多个位数不正确,它可以工作,但是如果不正确,则会弹出:

Traceback (most recent call last):
  File "&^%%@%#", line 5, in <module>
    while e[c] == ue[c]:
IndexError: string index out of range

我已经尝试过if语句,更多while语句和更多功能,但是它不起作用。这是代码:

e = str(2.7182818284590452353602874713526624977572470936999595)
ue = str(input("Copy in your version of e and this will check it ! "))

c = 0
while e[c] == ue[c]:
    if c < len(ue):
        c = c + 1
else:
    break

print(c - 1)

如果我输入2.79,则会显示3。 尽管如果我输入,请说2.718并且所有数字都是正确的,它会说:

IndexError: string index out of range (Coming from line 5)

(这也是我第一次参加Stack Overflow;所以请给我一些时间。)

1 个答案:

答案 0 :(得分:0)

您的问题是变量eue的长度不同。

将float转换为字符串时,会失去精度。

e = str(2.7182818284590452353602874713526624977572470936999595)
ue = input("Copy in your version of e and this will check it ! ")

print (e) # 2.718281828459045
print (ue) # 2.7182818284590452353602874713526624977572470936999595

doublesingle引号定义一个字符串:

e = '2.7182818284590452353602874713526624977572470936999595'
ue = input("Copy in your version of e and this will check it ! ")

c = 0
while e[c] == ue[c]:
    if c < len(ue)-1:
        c = c + 1
    else:
        break
print(c - 1)

输出:

Copy in your version of e and this will check it ! 2.7182818284590452353602874713526624977572470936999595
52