Python 如何将新变量定义为浮点数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34192842/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:35:35  来源:igfitidea点击:

How to define new variable as float?

python

提问by Shane Smiskol

I'm trying to make the following function output the correct answer, but the 'rightSide' variable is being made as an integer, and doesn't have any decimals.

我正在尝试使以下函数输出正确的答案,但 '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)!")

I just want all the variables to be floats, but the problem starts with 'rightSide'.

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

I tried the following with no success:

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

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

Any tips? Thanks!

有小费吗?谢谢!

Nevermind, I just re-ran the second code that I hand typed in the question and it worked -_-

没关系,我只是重新运行了我在问题中输入的第二个代码并且它起作用了-_-

采纳答案by hypersonics

Try this:

尝试这个:

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)!")

回答by intboolstring

In general

一般来说

x = float(2)

Or

或者

y = 10
x = float(y)

In your case,

在你的情况下,

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

回答by dimo414

You need to make one of the inputs a floating point value. Try changing 2to 2.0. E.g.:

您需要将输入之一设为浮点值。尝试更改22.0. 例如:

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

Note that in Python 3 division automatically returns a floating point, and the new //operator explicitly does integer division.

请注意,在 Python 3 中除法会自动返回一个浮点数,而 new//运算符显式地进行整数除法。