def sum_of_cubes(n):
sum_cubes = 0
for i in range(1, n+1):
sum_cubes += i3
return sum_cubes
n = 5
print(sum_of_cubes(n)) 输出:225
2. 使用`pow`函数:
def sum_of_cubes_with_pow(n):
sum_cubes = 0
for i in range(1, n+1):
sum_cubes += pow(i, 3)
return sum_cubes
n = 5
print(sum_of_cubes_with_pow(n)) 输出:225
3. 使用列表推导式和`sum`函数:
def sum_of_cubes_list_comprehension(n):
return sum([i3 for i in range(1, n+1)])
n = 5
print(sum_of_cubes_list_comprehension(n)) 输出:225
4. 使用`math.pow`函数:
import math
def sum_of_cubes_math_pow(n):
sum_cubes = 0
for i in range(1, n+1):
sum_cubes += math.pow(i, 3)
return sum_cubes
n = 5
print(sum_of_cubes_math_pow(n)) 输出:225
以上代码展示了如何使用不同的方法计算立方和。你可以选择最适合你需求的方法进行实现。