Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

python - Why is this division not performed correctly?

I've a strange issue in Python: the division is not performed correctly:

print pointB[1]
print pointA[1]
print pointB[0]
print pointA[0]
print  (pointB[1]-pointA[1]) / (pointB[0]-pointA[0])

These are the results:

100
50
100
40
0

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The above behavior is true for Python 2. The behavior of / was fixed in Python 3. In Python 2 you can use:

from __future__ import division

and then use / to get the result you desire.

>>> 5 / 2
2
>>> from __future__ import division
>>> 5 / 2
2.5

Since you are dividing two integers, you get the result as an integer.

Or, change one of the numbers to a float.

>>> 5.0 / 2
2.5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...