解决python的OverflowError: int too large to convert to float

解决python的OverflowError: int too large to convert to float

测试样例为:1000
错误代码:

def  main(): 
        num  =  eval(input()) 
        calculate_e(num) 
def calculate_e(n):
    t=1
    s=1
    for i in range(1,n+1):
        t=t*i
        s=s+1.0/t
    print('%.6f'%(s))
main() 

上述代码会出现报错:OverflowError: int too large to convert to float
应该改成如下,才正确:

def  main(): 
        num  =  eval(input()) 
        calculate_e(num) 
def calculate_e(n):
    t=1
    s=1
    for i in range(1,n+1):
        t=t*i
        s=s+1/t
    print('%.6f'%(s))
main() 

正确输出:
在这里插入图片描述

你可能感兴趣的:(python,python)