Python 練習(xí)實(shí)例76
題目:編寫一個(gè)函數(shù),輸入n為偶數(shù)時(shí),調(diào)用函數(shù)求1/2+1/4+...+1/n,當(dāng)輸入n為奇數(shù)時(shí),調(diào)用函數(shù)1/1+1/3+...+1/n(利用指針函數(shù))
程序分析:無。
程序源代碼:
#!/usr/bin/python # -*- coding: UTF-8 -*- def peven(n): i = 0 s = 0.0 for i in range(2,n + 1,2): s += 1.0 / i return s def podd(n): s = 0.0 for i in range(1, n + 1,2): s += 1 / i return s def dcall(fp,n): s = fp(n) return s if __name__ == '__main__': n = int(raw_input('input a number:\n')) if n % 2 == 0: sum = dcall(peven,n) else: sum = dcall(podd,n) print sum
以上實(shí)例輸出結(jié)果為:
input a number: 6 0.916666666667
更多建議: