這是我的老師給我們的問題:
撰寫一個程式來求以下系列的總和(從用戶那里接受 x 和 n 的值)。使用數學庫的函式,如 math.pow 和 math.factorial:1 x/1! x2/2! ……….xn/n!
這是我想出的代碼。我在紙上用簡單的數字計算出來,顯然有一些邏輯錯誤,因為我無法得到正確的答案。我想我一直在研究它太久才能真正掌握這個問題,所以我可以使用一些幫助。
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
for i in range (n):
power = math.pow(x,i)
ans = 1 (power / math.factorial(i))
print(ans)
注意:這是一個入門級課程,所以如果有更簡單的方法可以使用特定功能或其他東西我不能真正使用它,因為我還沒有被教過,盡管感謝任何輸入!
uj5u.com熱心網友回復:
我不建議使用這些功能。入門級程式員可以掌握更好的方法。
這是我建議您嘗試的方法:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
sum = 1
term = 1.0
for i in range (1,n 1):
term *= x/i
sum = term
print(sum)
你不需要這些功能。他們在這種情況下效率低下。
uj5u.com熱心網友回復:
我相信以下內容對您有用:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 1
for i in range (1,n 1):
power = math.pow(x,i)
ans = (power / math.factorial(i))
print(ans)
我們從 1 開始 ans 變數,并通過回圈的每次迭代將新術語添加到 ans 中。請注意,x =n這與整數相同x=x n。
我還更改了回圈的范圍,因為您從 1 開始并上升到 n,而不是從 0 開始并上升到 n-1。
輸出:
Input x: 2
Input n: 5
7.266666666666667
對于熟悉數學常數 e 的人:
Input x: 1
Input n: 15
2.718281828458995
uj5u.com熱心網友回復:
您ans只包括(1 和)最新的術語。相反,您應該在回圈之前對其進行初始化,然后將所有術語添加到其中。第一項 1 不值得丑陋的特殊處理,所以我像所有其他人一樣計算它:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
ans = 0
for i in range(n 1):
ans = math.pow(x, i) / math.factorial(i)
print(ans)
并預覽您可能很快會被教導/允許如何撰寫它:
import math
x = int(input ("Input x: "))
n = int(input("Input n: "))
print(sum(math.pow(x, i) / math.factorial(i)
for i in range(n 1)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426848.html
上一篇:如何簡化下圖中共享的代碼?
下一篇:可選函式引數哪個子集串列?
