2.7.4上的Python的/和//运算符 [英] Python's / and // operators on 2.7.4

查看:47
本文介绍了2.7.4上的Python的/和//运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我开始学习基础知识.我是C ++人,所以//运算符是新的东西.根据我正在阅读的书:

I am new to Python and I started studying the basics. I am a C++ guy so the // operator was something new. According with a book that I am reading:

>> 4/2
2.0
>> 2/4
0.5
>> 5//4
2
>> 2//4
0

问题在于,当我写5//4时,结果是1;当我写4/2时,结果是2而不是2.0;当我写2/4时,结果是0.我必须写"2.0/4.0",结果为0.5.这些作者的错误还是我做错了?

The problem is that when I write 5//4 the result is 1,when I write 4/2 the result is 2 and not 2.0 and when I write 2/4 the result is 0 . I have to write `2.0/4.0' to have 0.5 as the result. Is these author's mistakes or am I doing something wrong?

我正在linux2上使用Python 2.7.4,[GCC 4.7.3]

I am using Python 2.7.4, [GCC 4.7.3] on linux2

推荐答案

在Python 2.x中,默认的除法运算符为经典除法".这意味着/与整数运算符一起使用时,将导致类似于C ++或java的整数除法. 4/3 = 1].

In Python 2.x, the default division operator is "Classic division". This means that /, when used with integer operators will result in integer division similar to C++ or java [i.e. 4/3 = 1].

在Python 3.x中,这已更改.此处,/表示真实划分" [4/3 = 1.3333..],而//用于请求经典/地板划分".

In Python 3.x, this is changed. There, / refers to "True division" [4/3 = 1.3333..], whereas // is used to request "Classic/Floor division".

如果要在Python 2.7中启用真除法",则可以在代码中使用from __future__ import division.

If you want enable "True division" in Python 2.7, you can use from __future__ import division in your code.

来源: PEP 238

例如:

>>> 4/3
1
>>> 4//3
1
>>> from __future__ import division
>>> 4/3
1.3333333333333333
>>> 4//3
1

这篇关于2.7.4上的Python的/和//运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆