gpt4 book ai didi

python - 类型错误 : can only concatenate str (not "int") to str SUM

转载 作者:行者123 更新时间:2023-11-30 22:06:35 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,将数字的立方求和到上限。

数学公式为(n*(n+1)/2)^2

我的Python代码:

def cube_numbers():
upper_boundary = 0
cube_sum = 0
upper_boundary = input("Please enter the upper boundary:")
cube_sum = ((upper_boundary * (upper_boundary + 1) / 2)**2)
print("The sum of the cube of numbers up to" & upper_boundary & "is" & cube_sum)
#main
cube_numbers()

但是我收到以下错误:

  Traceback (most recent call last):

File "C:/Users/barki/Desktop/sum of cubes.py", line 10, in <module>
cube_numbers()

File "C:/Users/barki/Desktop/sum of cubes.py", line 5, in cube_numbers
cube_sum = ((upper_boundary * (upper_boundary + 1) / 2)**2)
TypeError: can only concatenate str (not "int") to str

最佳答案

您的函数的目的不应该是打印。此外,最好将输入提示移出函数,然后将该值传递到函数中。然后我们可以做的是获取 upper_boundary 作为 int 的输入,然后将其传递给 cube_numbers。该返回值现在将为 cube_sum,我们可以使用格式化打印来打印该语句。

def cube_numbers(x):
y = int(((x * (x + 1) / 2)**2))
return y

upper_boundary = int(input("Please enter the upper boundary: "))
cube_sum = cube_numbers(upper_boundary)

print('The sum of the cube of numbers up to {} is {}.'.format(upper_boundary, cube_sum))
# The sum of the cube of numbers up to 10 is 3025.

关于python - 类型错误 : can only concatenate str (not "int") to str SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52682634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com