菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python 练习实例76

Python 100例 Python 100例

题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n

程序分析:无。

程序源代码:

实例(Python 2.0+)

#!/usr/bin/python# -*- coding: UTF-8 -*-defpeven(n): i = 0s = 0.0foriinrange(2,n + 1,2): s += 1.0 / i# Python里,整数除整数,只能得出整数,所以需要使用 浮点数 1.0returnsdefpodd(n): s = 0.0foriinrange(1, n + 1,2): s += 1.0 / i# Python里,整数除整数,只能得出整数,所以需要使用 浮点数 1.0returnsdefdcall(fp,n): s = fp(n)returnsif__name__ == '__main__': n = int(raw_input('input a number:\n'))ifn % 2 == 0: sum = dcall(peven,n)else: sum = dcall(podd,n)printsum

以上实例输出结果为:

input a number:
6
0.916666666667

Python 100例 Python 100例

AI 思考中...

5 篇笔记 写笔记

  1. #0

    CosmosHua

    cos***[email protected]

    40

    Python3 测试实例:

    def sumfr(n):
     ls = [1/i for i in range(n,0,-2)]
     return sum(ls)
    sumfr(6) #结果: 0.9166666666666666
    sumfr(5) #结果:1.5333333333333332

    CosmosHua

    cos***[email protected]

    9年前 (2017年07月13日)
  2. #0

    凤凰竹人

    694***[email protected]

    1

    Python3 测试实例:

    #!/usr/bin/python3
    # -*- coding: UTF-8 -*-
    def qiuhe():
     n=int(input('请输入任意正整数:'))
     i,j,sum=1,0,0
     if n==1:
     print('当前结果为:',sum+1)
     elif n%2==0: #偶数
     while 2*i<=n:
     sum+=1/(2*i)
     i+=1
     print('当前结果为:',sum)
     elif n%2!=0:
     while (2*j+1)<=n:
     sum+=1/(2*j+1)
     j+=1
     print('当前结果为:',sum)
    qiuhe()
    

    凤凰竹人

    694***[email protected]

    9年前 (2017年07月18日)
  3. #0
    0

    参考方法:

    def fun(num):
     s = 0.0
     if int(num) % 2 == 0:
     for i in range(2,int(num)+1,2):
     s+=1.0/i
     else:
     for i in range(1,int(num)+1,2):
     s+=1.0 / i
     return s
    num = raw_input("please input a num:\n")
    print fun(num)
    
    9年前 (2017年08月17日)
  4. #0

    随风奔跑的女子

    318***[email protected]

    4

    Python3 用的递归

    def sum(n):
     if n==1:
     return 1
     elif n==2:
     return 1/2
     elif n%2==0:
     return (1/n+sum(n-2))
     elif n%2==1:
     return (1/n+sum(n-2))
    n=int(input("input a number:\n"))
    print(sum(n))
    

    随风奔跑的女子

    318***[email protected]

    9年前 (2017年10月09日)
  5. #0

    iMax4ever

    jia***@foxmail.com

    3

    Python3:在 CosmosHua 的基础上:

    print(sum([1/i for i in range(int(input('Enter another integer:')), 0, -2)])

    iMax4ever

    jia***@foxmail.com

    9年前 (2017年10月13日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /