简体   繁体   中英

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). 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 . Using %d for floats will print only it's decimal part.

>>> 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.

To fix that you should convert at least one of the operand to float.

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

or import python3.x's divison :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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