我的简单python程序不断收到此错误:“TypeError:'float'对象不能解释为整数”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19824721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"
提问by remorath
I don't understand why I can't use my variable c
.
我不明白为什么我不能使用我的变量c
。
code:
代码:
from turtle import *
speed(0)
hideturtle()
c = 450
def grid(x,y,a):
seth(0)
pu()
goto(x,y)
pd()
for i in range(4):
forward(a)
rt(90)
for i in range(c/10):
seth(0)
forward(10)
rt(90)
forward(c)
backward(c)
for i in range(c/10):
seth(0)
rt(90)
forward(10)
rt(90)
forward(c)
backward(c)
pu()
goto(a+10,0)
write("x")
goto(0,a+10)
write("y")
pd()
grid(0,0,c)
grid(-c,0,c)
grid(-c,c,c)
grid(0,c,c)
I get the following error message:
我收到以下错误消息:
Traceback (most recent call last):
File "C:\Users\nick\Desktop\gridv2.py", line 35, in <module>
grid(0,0,c)
File "C:\Users\nick\Desktop\gridv2.py", line 15, in grid
for i in range(c/10):
TypeError: 'float' object cannot be interpreted as an integer
采纳答案by Jon Clements
In:
在:
for i in range(c/10):
You're creating a float as a result - to fix this use the int division operator:
因此,您正在创建一个浮点数 - 要解决此问题,请使用 int 除法运算符:
for i in range(c // 10):
回答by Martijn Pieters
range()
can only work with integers, but dividing with the /
operator always results in a float value:
range()
只能处理整数,但与/
运算符相除总是会产生浮点值:
>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
Make the value an integer again:
再次将该值设为整数:
for i in range(int(c / 10)):
or use the //
floor division operator:
或使用//
楼层除法运算符:
for i in range(c // 10):
回答by Jon Clements
As shown below, range
only supports integers:
如下图,range
只支持整数:
>>> range(15.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got float.
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>
However, c/10
is a float because /
always returns a float.
然而,c/10
是一个浮点数,因为/
总是返回一个浮点数。
Before you put it in range
, you need to make c/10
an integer. This can be done by putting it in int
:
在你把它放进去之前range
,你需要做c/10
一个整数。这可以通过将其放入来完成int
:
range(int(c/10))
or by using //
, which returns an integer:
或通过 using //
,它返回一个整数:
range(c//10)