For循环不工作,说明端点是浮点数



对于上下文,我正在编写一个需要Guass公式的程序。它被用来查找,例如,5 + 4 + 3 + 2 + 1,或8 + 7 + 6 + 5 + 4 + 3 + 2 + 1。

公式为(n*(n + 1))/2,我试图将其合并到for循环中,但我得到一个错误声明:

'float'对象不能解释为整数';

这是我的代码:

# Defining Variables #
print("Give me a start")
x = int(input())
print("Give me a delta")
y = int(input())
print("Give me an amount of rows")
z = int(input())
archive_list = []
f = z + 1
stop = z*f
final_stop = stop/2
# Main Logic #
for loop in range(1,final_stop,1):
print("hi")

如果你能回答为什么它不能像固定代码那样工作,我将非常感激。

提前感谢!

正如@ForceBru在他的精彩评论中指出的那样,问题是端点final_stop是浮点数,而不是整型。原因是在计算它时使用了单/而不是双/。如果你替换掉final_stop = stop/2final_stop = stop//2,那应该没问题。

最新更新