寫一個 Python 程序計算數列 1 +2 +3 +的和……+n 用 For 循環和函數舉例。
級數 1 +2 +3 +的 Python 和的數學公式。+n = ( n (n+1) / 6)
這個 Python 程序允許用戶輸入任意正整數。接下來,Python 找到系列 1 +2 +3 +的和……+n 使用上述公式。
# Python Program to calculate Sum of Series 1³+2³+3³+….+n³
import math
number = int(input("Please Enter any Positive Number : "))
total = 0
total = math.pow((number * (number + 1)) /2, 2)
print("The Sum of Series upto {0} = {1}".format(number, total))
系列 1 +2 +3 +的 Python 和……+n 使用數學功率輸出
Please Enter any Positive Number : 7
The Sum of Series upto 7 = 784.0
求和=冪((數(數+ 1)) / 2),2)
=冪((7 (7 + 1)) / 2),2)
求和=冪((7 * 8) / 2),2) = 784
如果想讓 Python 顯示系列 1 +2 +3 +…。+n 訂單,我們必須添加額外的循環和 If Else 。
import math
number = int(input("Please Enter any Positive Number : "))
total = 0
total = math.pow((number * (number + 1)) /2, 2)
for i in range(1, number + 1):
if(i != number):
print("%d^3 + " %i, end = ' ')
else:
print("{0}^3 = {1}".format(i, total))
第 1 系列 python+2г+3℃+nг輸出
Please Enter any Positive Number : 5
1^3 + 2^3 + 3^3 + 4^3 + 5^3 = 225.0
這個系列 1 +2 +3 +的 Python 和……+n 程序同上。然而,在這個 Python 程序中,我們定義了一個函數來放置邏輯。
import math
def sum_of_cubes_series(number):
total = 0
total = math.pow((number * (number + 1)) /2, 2)
for i in range(1, number + 1):
if(i != number):
print("%d^3 + " %i, end = ' ')
else:
print("{0}^3 = {1}".format(i, total))
num = int(input("Please Enter any Positive Number : "))
sum_of_cubes_series(num)
Please Enter any Positive Number : 7
1^3 + 2^3 + 3^3 + 4^3 + 5^3 + 6^3 + 7^3 = 784.0
這裡,我們使用 Python 遞歸函數來求數列 1 +2 +3 +的和。+n。
def sum_of_cubes_series(number):
if(number == 0):
return 0
else:
return (number * number * number) + sum_of_cubes_series(number - 1)
num = int(input("Please Enter any Positive Number : "))
total = sum_of_cubes_series(num)
print("The Sum of Series upto {0} = {1}".format(num, total))
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/126326.html