我已经看了很多贴在这里的问题,但找不到答案。这是导致问题的代码片段:
常数:
antvelocity=float(10) #pixels per frame
代码的另一部分(randir()是一个全局函数):
def randir():
n=float(random.randint(0,8))
ang=(n*math.pi)/4
蚂蚁类:
class Ant:
antx=0
anty=0
id=0
def __init__(self,id):
self.id=id
def draw(self):
SCREEN.blit(antimg,(self.antx,self.anty))
def seek(self):
randang=randir()
velx=math.floor(float(antvelocity)*float(math.cos(randang)))
vely=math.floor(float(antvelocity)*float(math.sin(randang)))
self.antx=self.antx+velx
self.anty=self.anty+velx
self.draw()
pygame.display.update()
#Handling code for seeking
def carry(self):
pass
#Handling code for carrying leaf
+++++++++++++++++++++++++++++++++++++++错误+++++++++++++++++++++++++++++++++++
Traceback (most recent call last):
File "/home/acisace/Python Projects/Gathering/gather.py", line 101, in <module>
ant1.seek()
File "/home/acisace/Python Projects/Gathering/gather.py", line 64, in seek
velx=math.floor(float(antvelocity)*float(math.cos(randang)))
TypeError: a float is required
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
请帮我纠正这个问题
谢谢大家。真不敢相信我错过了。
看起来
randir
正在返回None
,这不是一个浮点数。(如果未在任何给定函数中指定返回值,则默认情况下将返回None
。)然后将结果(存储在randang
)传递给cos
,该结果仅为浮点定义。只需添加:到
randir
结尾。因为第二行代码似乎是问题所在,最可能的原因是
randang
,因为float()
不需要浮点数,如果你做了类似float('a')
这样的蠢事,你会得到一个不同的错误:实际上,对
randir
的定义说明了为什么:它并没有明确地返回任何东西,意味着您将得到
None
。作为一个简单的例子,请参阅以下文本:
您需要从您的
randir()
函数返回一个float(或者一些可以变成float的东西):在您的情况下,函数应该是:
您的
randir()
函数不返回任何内容:因此
None
被返回:然后将该
None
值传递给math.cos()
:从而引发您的错误:
如果要修复此问题,必须向函数中添加
return
语句:相关问题 更多 >
编程相关推荐