Python两个整数相除得到浮点数值的方法

WBOY
Release: 2016-06-06 11:22:24
Original
2087 people have browsed it

在python中进行两个整数相除的时候,在默认情况下都是只能够得到整数的值,而在需要进行对除所得的结果进行精确地求值时,想在运算后即得到浮点值,那么如何进行处理呢?

1、修改被除数的值为带小数点的形式即可得到浮点值,这种方法在被除数事先知道的情况下才可以采用有效,而这种情况意味着被除数的值是写死的、固定的,在绝大多数的情况下是不可行的;

2、在进行除法运算前导入一个实除法的模块,即可在两个整数进行相除的时候得到浮点的结果;

代码如下:


from __future__ import division


以下为测试的结果:

代码如下:


ufo@ufo:~$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:56)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 244158112/1024
238435
####注意以上的运算结果为整数
####导入实除法模块后的结果为浮点数
>>> from __future__ import division
>>> 244158112/1024
238435.65625
>>> 244158112/1024/1024
232.84732055664062

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!