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