“需要浮动”

2024-09-24 22:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经看了很多贴在这里的问题,但找不到答案。这是导致问题的代码片段:

常数:

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

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

请帮我纠正这个问题


谢谢大家。真不敢相信我错过了。


Tags: 代码selfiddefseekmathfloatdraw
3条回答

看起来randir正在返回None,这不是一个浮点数。(如果未在任何给定函数中指定返回值,则默认情况下将返回None。)然后将结果(存储在randang)传递给cos,该结果仅为浮点定义。只需添加:

return ang

randir结尾。

randang=randir()
velx=math.floor(float(antvelocity)*float(math.cos(randang)))

因为第二行代码似乎是问题所在,最可能的原因是randang,因为float()不需要浮点数,如果你做了类似float('a')这样的蠢事,你会得到一个不同的错误:

ValueError: could not convert string to float: a

实际上,对randir的定义说明了为什么:

def randir():
    n=float(random.randint(0,8))
    ang=(n*math.pi)/4

它并没有明确地返回任何东西,意味着您将得到None

作为一个简单的例子,请参阅以下文本:

>>> def nothing():
...     pass
...

>>> print nothing()
None

>>> import math
>>> print math.cos(nothing())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a float is required

您需要从您的randir()函数返回一个float(或者一些可以变成float的东西):

>>> def nothing():
...     return 0.5
...

>>> print nothing()
0.5

>>> import math
>>> print math.cos(nothing())
0.87758256189

在您的情况下,函数应该是:

def randir():
    n = float(random.randint(0,8))
    ang = (n * math.pi) / 4
    return ang

您的randir()函数不返回任何内容:

def randir():
    n=float(random.randint(0,8))
    ang=(n*math.pi)/4

因此None被返回:

>>> import random, math
>>> def randir():
...     n=float(random.randint(0,8))
...     ang=(n*math.pi)/4
... 
>>> randir()
>>> randir() is None
True

然后将该None值传递给math.cos()

math.cos(randang)

从而引发您的错误:

>>> math.cos(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a float is required

如果要修复此问题,必须向函数中添加return语句:

def randir():
    n=float(random.randint(0,8))
    ang=(n*math.pi)/4
    return ang

相关问题 更多 >