-1

I am just trying to compute some basic arithmetic, but python won't stop rounding to the nearest integer.

For example, when I input

print float(3 * 1/(1*2) + 1)

it outputs 2.0 rather than 2.5; I can't figure out how to keep it from rounding like this. I would appreciate any help you can provide.

  • put brackets for python 3, otherwise it looks alright to me. However, instead of casting to float, you ca do this `print(3 * 1.0/(1*2) + 1)` with the same effect – VnC Jul 01 '19 at 15:02
  • 2
    Python 2. Integer division. 3 / 2 = 1. – Matthias Jul 01 '19 at 15:02

2 Answers2

1

Add a dot (.) to indicate floating point numbers, or indicate number as float (float(1))

>>> print (3 * 1/(1*2) + 1)
2.0
>>> print (3 * 1./(1*2) + 1)
2.5
>>> print (3 * float(1)/(1*2) + 1)
2.5

In Python 3, / is float division

In Python 2, / is integer division (assuming int inputs)

In both Python 2 and 3, // is integer division

(To get float division in Python 2 requires either of the operands to be a float, either as 20. or float(20))

NOTE:

in Python 2.2 - 2.7 you can do from __future__ import division to get Python 3's behavior

ncica
  • 7,015
  • 1
  • 15
  • 37
-1

In python 2, int/int = int try casting int to float

print float(3 * 1)/float(1*2) + 1

or

print float(3 * 1)/(1*2) + 1
Rahul Raut
  • 1,099
  • 8
  • 15