在 Python 中使用除法运算符时如何获得十进制值? [英] How do I get a decimal value when using the division operator in Python?

查看:25
本文介绍了在 Python 中使用除法运算符时如何获得十进制值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,标准除法符号/"四舍五入为零:

<预><代码>>>>4/1000

但是,我希望它返回 0.04.我用什么?

解决方案

共有三个选项:

<预><代码>>>>4/浮动 (100)0.04>>>4/100.00.04

这与 C、C++、Java 等的行为相同,或者

<预><代码>>>>来自 __future__ 进口部门>>>4/1000.04

您也可以通过将参数 -Qnew 传递给 Python 解释器来激活此行为:

$ python -Qnew>>>4/1000.04

第二个选项将是 Python 3.0 中的默认选项.如果要进行旧的整数除法,则必须使用 // 运算符.

编辑:添加了关于 -Qnew 的部分,感谢 ΤΖΩΤΖΙΟΥ!

For example, the standard division symbol '/' rounds to zero:

>>> 4 / 100
0

However, I want it to return 0.04. What do I use?

There are three options:

>>> 4 / float(100)
0.04
>>> 4 / 100.0
0.04

which is the same behavior as the C, C++, Java etc, or

>>> from __future__ import division
>>> 4 / 100
0.04

You can also activate this behavior by passing the argument -Qnew to the Python interpreter:

$ python -Qnew
>>> 4 / 100
0.04

The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the // operator.

Edit: added section about -Qnew, thanks to ΤΖΩΤΖΙΟΥ!

这篇关于在 Python 中使用除法运算符时如何获得十进制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆