Python对小数进行除法运算的正确方法示例

WBOY
Release: 2016-06-06 11:32:43
Original
1964 people have browsed it

求一个算式

代码如下:


a=1
b=2
c=3
 
print c*(a/b)


运行结果总是0,反复检查拆开以后,发现在Python里,整数初整数,只能得出整数。
也就是 a 除 b 这个结果永远是0,只要把a或者b其中一个数改成浮点数即可。

代码如下:


a=1
b=2
c=3
 
print c*(a/float(b))
print c*(float(a)/b)


这样才能准确算出a除b的正确结果,当然,如果a比b大,并且不需要小数位数部分可以不用float。
如:

代码如下:


a=1
b=2
c=3
 
print c/a # 3
print c/b # 1
print c/float(b )# 1.5

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!