python 圆问题
我在分割时遇到问题
my max_sum = 14
total_no=4
,所以当我分割时
print "x :", (total_sum/total_no)
,我得到 3 而不是 3.5
我尝试了很多打印方法但失败了,有人可以告诉我如何得到 3.5 格式吗?
谢谢
I am facing the problem while dividing
my max_sum = 14
total_no=4
so when i do
print "x :", (total_sum/total_no)
, I get 3 and not 3.5
I tried many ways for printing but failed, can somebody let me know what way I get in 3.5 format?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 Python 2.x 中,默认情况下将两个整数相除会得到另一个整数。这常常令人困惑,并已在 Python 3.x 中得到修复。您可以通过将其中一个数字转换为浮点数来绕过它,这将自动转换另一个数字:
float( 14 ) / 4 == 3.5
相关的 PEP 是 编号 238:
由于严重的向后兼容性问题,它在 Python 2.x 中没有发生变化,但它是 Python 3.x 中的主要变化之一。 行强制进行新的划分
您可以使用Python 脚本顶部的 。这是一个
__future__
-import -- 它用于强制更改语法,否则可能会破坏脚本。还有许多其他__future__
导入;在准备迁移到 Python 3.x 时使用它们通常是一个好主意。请注意,
//
运算符始终表示整数除法;如果您确实想要这种行为,您应该优先使用它而不是/
。请记住,“显式优于隐式”!In Python 2.x, dividing two integers by default dives you another integer. This is often confusing, and has been fixed in Python 3.x. You can bypass it by casting one of the numbers to a float, which will automatically cast the other:
float( 14 ) / 4 == 3.5
The relevant PEP is number 238:
It was not changed in Python 2.x because of severe backwards-compatibility issues, but was one of the major changes in Python 3.x. You can force the new division with the line
at the top of your Python script. This is a
__future__
-import -- it is used to force syntax changes that otherwise might break your script. There are many other__future__
imports; they are often a good idea to use in preparation for a move to Python 3.x.Note that the
//
operator always means integer division; if you really want this behaviour, you should use it in preference to/
. Remember, "explicit is better than implicit"!在 python 2 中,您正在除两个整数,结果也将是一个整数。尝试将您的操作数之一设置为浮点数,例如
max_sum = 14.0
或total_no = 4.0
得到一个浮点结果。如果您希望 python 2.X 在这方面表现得更直观,您可以
在脚本顶部添加。在 python 3 中,除法按照您的预期工作。
You are dividing two integers, the result will be an integer too, in python 2. Try make one of your operands a float, like
max_sum = 14.0
ortotal_no = 4.0
to get a float result.If you want python 2.X behave a bit more intuitive in that matter you can add
on the top of your script. In python 3, division works as you expected it in your case.
使 max_sum=14.0 或total_no=4.0
make max_sum=14.0 or total_no=4.0
您正在进行整数运算,以便获得最接近的整数结果: 3.
您应该显式/隐式地将
max_sum
或total
转换为浮点数。You're doing an integer operation so you get the nearest integer result : 3.
You should either explicitly/implicitly cast
max_sum
ortotal
to float.另一种方法是从 Python 3 导入除法:
Another way of doing this would be to import division from Python 3: