如何将新变量定义为float?

2024-04-28 22:21:41 发布

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

我正试图使下面的函数输出正确的答案,但是“rightSide”变量被设置为整数,并且没有任何小数。

def G(mass1, mass2, radius, force):
    rightSide=(mass1*mass2)/(radius**2) #I want this to be a float
    print rightSide
    if rightSide==0:
        print("The operation resulted in a zero, error!")
    else:
        answer=force/rightSide
        print(str(answer)+" is the gravitation constant (G)!")

我只希望所有的变量都是浮点数,但问题从“rightSide”开始。

我尝试了以下方法,但没有成功:

float(rightSide)=(mass1*mass2)/(radius**2)
  --
rightSide=(float(mass1)*float(mass2))/(float(radius)**2)

有什么建议吗?谢谢!

不管怎样,我只是重新运行了我在问题中手工输入的第二个代码,它成功了-


Tags: 函数答案answerdef整数floatprintforce
3条回答

总的来说

x = float(2)

或者

y = 10
x = float(y)

对你来说

rightSide=float((mass1*mass2)/(radius**2))

试试这个:

def G(mass1, mass2, radius, force):
    rightSide = (float(mass1)*mass2) / (radius**2) #I want this to be a float
    print rightSide
    if rightSide==0:
        print("The operation resulted in a zero, error!")
    else:
        answer=force/rightSide
        print(str(answer)+" is the gravitation constant (G)!")

您需要将其中一个输入设为浮点值。尝试将2更改为2.0。E、 g.:

>>> x=10
>>> x**2
100
>>> x**2.0
100.0

注意,在Python 3division automatically returns a floating point中,新的//运算符显式地执行整数除法。

相关问题 更多 >