1 + 1 / 2! + 1/ 3! + ¼! + …… Finding Sum [duplicate]

纵然是瞬间 提交于 2020-01-03 04:38:45

问题


Q. ) 1 + 1 / 2! + 1/ 3! + ¼! + ….....
The output of the following program is always 1.0. I'm a python beginner. Please tell me what's wrong? Please suggest any other methods to make this program better. No inbuilt functions, please. I want to do this manually.

    n=int(raw_input("Enter number of terms : ")) 

    d=0  #to sum all terms, initial value is 0

while n>0:
     j=n   #we start by taking factorial of the last term
     s=1   #to multiply to find factorial
     while j>0:
               s=s*j   #number gets multiplied to s and stored in s
               j=j-1   #number is decreased until it reaches 0
     n=n-1   #we will keep finding factorial until the very first term, i.e. 1 is reached
     x=float(1/s)   #to find reciprocal of the factorial we just found in     floating point
     d=d+x #adding to final sum

print "Sum of 1+1/2!+1/3!+1/4!+.... is ",d #printing

回答1:


You need to use float somewhere in your division. I just make you "s" a float.

n=int(raw_input("Enter number of terms : ")) 

d=0  #to sum all terms, initial value is 0

while n>0:
     j=n   #we start by taking factorial of the last term
     s=float(1)   #to multiply to find factorial
     while j>0:
               s=s*j   #number gets multiplied to s and stored in s
               j=j-1   #number is decreased until it reaches 0
     n=n-1   #we will keep finding factorial until the very first term, i.e. 1 is reached
     x=1/s   #to find reciprocal of the factorial we just found in     floating point
     d=d+x #adding to final sum

print "Sum of 1+1/2!+1/3!+1/4!+.... is ",d #printing


来源:https://stackoverflow.com/questions/31323495/1-1-2-1-3-%c2%bc-finding-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!