How to 'print' the result of a division in Ironpython (Python.net)?
I need to print the result of 'x/y' but it always returns '0'. When I print 'x' it tells me that correctly, when I print 'y' it tells me that correctly but when I print 'x/y' it says 0.
Here is my code:
import random
y = 0
x = 0
p = 1
while True:
i = [random.randint(1,100), random.randint(1,100), random.randint(1,100), random.randint(1,100), random.randint(1,100)]
if len(set(i)) < len(i):
print "Match!"
x += 1
y += 1
print(x/开发者_开发百科y)
else:
print "No Match!"
y += 1
print y
Like I said, it prints y
fine when it's supposed to, but in the events that it needs to print x/y
it prints 0
. I have also tried print x/y
and print x//y
but they don't work either.
What am I doing wrong?
Thanks in advance
If x and y are both integers, Python always does integer division. So if the result is 0.something, Python will show 0.
You need to convert them to floats if you want to do float division:
print float(x) / float(y)
or Decimal
objects:
from decimal import Decimal
print Decimal(x) / Decimal(y)
Do this
from __future__ import division
Read this
http://www.python.org/dev/peps/pep-0238/
I thought it might be useful to point out the part of that PEP that's most relevant here:
The correct work-around is subtle: casting an argument to float() is wrong if it could be a complex number; adding 0.0 to an argument doesn't preserve the sign of the argument if it was minus zero. The only solution without either downside is multiplying an argument (typically the first) by 1.0. This leaves the value and sign unchanged for float and complex, and turns int and long into a float with the corresponding value.
So, you can do:
print 1.0 * x / y
Try:
print float(x)/float(y)
Integer division always truncates the decimal.
Also note that only the numerator actually needs to be a float, but it is better to be explicit about what you are doing.
精彩评论