简体   繁体   English

在特殊情况下,强制除法在Python中是浮点数

[英]Forcing division to be floating-point in Python in a special case

This code prints 17, but I want the division to be performed using floating-point (so it should print 17.5 instead). 此代码打印17,但我希望使用浮点执行除法(因此它应该打印17.5而不是)。 How can I force the division to be in floating-point? 如何强制分区处于浮点状态?

math = 8
physics = 9.5
algebra = 7.50
geometry = 10

**print "My GPA is %d" % ((math + physics + algebra + geometry)/2)**

%d is used for integers, for floats use %f . %d用于整数,浮点数用于%f Using %d for floats will print only it's decimal part. 使用%d表示浮点数只会打印它的小数部分。

>>> print "My GPA is %f" % ((math + physics + algebra + geometry)/2)
My GPA is 17.500000

or: 要么:

>>> print "My GPA is %.1f" % ((math + physics + algebra + geometry)/2)
My GPA is 17.5

Using new style string formatting: 使用新样式字符串格式:

>>> print "My GPA is {:.1f}" .format((math + physics + algebra + geometry)/2)
My GPA is 17.5

Also note that integer division in py2.x truncates the output and returns an integer. 另请注意,py2.x中的整数除法会截断输出并返回一个整数。

To fix that you should convert at least one of the operand to float. 要解决此问题,您应该将至少一个操作数转换为float。

>>> 3/2
1
>>> 3/float(2)
1.5
>>> 3/2.
1.5

or import python3.x's divison : 或者导入python3.x的divison

>>> from __future__ import division
>>> 3/2
1.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM