编写一个Python程序,使用For循环和函数计算级数 1³+2³+3³+….+n³ 的和,并附带示例。
Python级数和 1³+2³+3³+….+n³ 的数学公式 = ( n (n+1) / 6)²
Python程序计算级数 1³+2³+3³+….+n³ 的和
此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))
Python级数和 1³+2³+3³+….+n³ 使用math.pow输出
Please Enter any Positive Number : 7
The Sum of Series upto 7 = 784.0
Sum = pow (((Number * (Number + 1)) / 2), 2)
= pow (((7 * (7 + 1)) / 2), 2)
Sum = pow (((7 * 8) / 2), 2) = 784
Python程序计算级数 1³+2³+3³+….+n³ 的和 示例 2
如果您希望Python显示级数 1³+2³+3³+….+n³ 的顺序,我们需要在 If Else 语句中添加额外的 For 循环。
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))
Python级数和 1³+2³+3³+….+n³ 输出
Please Enter any Positive Number : 5
1^3 + 2^3 + 3^3 + 4^3 + 5^3 = 225.0
Python程序使用函数计算级数 1³+2³+3³+….+n³ 的和
此Python级数和 1³+2³+3³+….+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³ 的和
在这里,我们使用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))
