-1

This gives output as 0:

print -4/-5 

Whereas:

print float(-4/-5)

This gives output as 0.0 . The required output is 0.8

Sarthak Agarwal
  • 128
  • 1
  • 2
  • 16
Sanj
  • 119
  • 1
  • 3
  • 9

3 Answers3

2

You are doing integer division instead of floating point division. It has been answered already: Python division .

Casting types after the division doesn't make sense.

float(4)/float(5)

Or simpler

4./5.

should do the trick

Community
  • 1
  • 1
jhoepken
  • 1,842
  • 3
  • 17
  • 24
2

To understand,

print float(-4/-5)

Bracket is calculated first. Value given to float is 0. Typecasting 0 to 0.0

This will give the required output:

print float(-4)/-5
Sarthak Agarwal
  • 128
  • 1
  • 2
  • 16
1

/ does integer division.

To get your desired output, the operands should be float (either or both).

-4.0 / -5.0 = 0.8

To explain the second code snippet, the first one to be evaluated is the operation -4 / -5 which results to 0 since we did an integer division. Now what you tried to do is to convert 0 to a floating point using the function float(). Converting that resulted to 0.0

krato
  • 1,226
  • 4
  • 14
  • 30