简体   繁体   English

C ++和Python中/之间的区别

[英]Difference between / in C++ and Python

Using Python 2.7 使用Python 2.7

I was trying to solve the Reverse Polish Notation problem on LeetCodeOJ. 我正在尝试解决LeetCodeOJ上的反向波兰语表示法问题。

RPN on LeetCodeOJ 在LeetCodeOJ上的RPN

I wrote my straightforward solution in Python as follows: 我用Python编写了简单的解决方案,如下所示:

class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
    stack = []
    for token in tokens:
        if token in ["+" , "-" ,"*", "/"]:
            op1 = stack.pop()
            op2 = stack.pop()
            if token == "+":
                stack.append(op2+op1)
            elif token == "-":
                stack.append(op2-op1)
            elif token == "*":
                stack.append(op2*op1)
            elif token == "/":
                stack.append(op2/op1)
        else:
            stack.append(int(token))
    if len(stack) == 1:
        return stack.pop()
    else:
        return 0

This gets rejected on a test case: 这在测试案例中被拒绝:

Input:  ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 12
Expected: 22

But if I modify the application of '/' operation to stack.append(int(op2 / (op1*1.0))) , it succeeds. 但是如果我将'/'操作的应用程序修改为stack.append(int(op2 / (op1*1.0))) ,它将成功。

The / operation is performed once on this input calculating 6/-132 which results in -1 using either of two ways. 对此输入计算6/-132进行一次/操作,使用两种方法之一得出-1

Strangely, despite the fact that both evaluations result in -1 , the program as a whole differs in its output. 奇怪的是,尽管两个评估结果均为-1 ,但该程序的整体输出却有所不同。 As shown above, using the first way gives 12 as the RPNEval while using the second would give 22 . 如上所示,使用第一种方法将获得12作为RPNEval,而使用第二种方法将获得22 What causes this? 是什么原因造成的?

I visited this link , but it only says that there is some difference in the / operator in Python and C++. 我访问了此链接 ,但它仅表示Python和C ++中的/运算符有所不同。 What is the difference? 有什么区别?

If you are on Python 2, / does integer division (meaning, it drops the remainder and just gives you the rounded-down result) unless at least one of the operands is of type float rather than int . 如果您使用的是Python 2,则/整数除法(即,它会除掉余数并只给出四舍五入的结果),除非至少一个操作数的类型为float而不是int类型。 You fix this by multiplying with 1.0 , but you could also call float(...) on one of the operands. 您可以通过乘以1.0解决此问题,但是您也可以在其中一个操作数上调用float(...) This is similar to C++, however, in C++ the result is rounded towards zero rather than down , meaning that you will receive different results with one negative operand: 这类似于C ++,但是在C ++中,结果四舍五入为零而不是向下取整,这意味着使用一个负操作数将收到不同的结果:

C++: C ++:

1 / 2       // gives 0
(-1) / 2    // also gives 0

Python 2: Python 2:

1 / 2       # gives 0
(-1) / 2    # gives -1 (-0.5 rounded down)

Python 3: Python 3:

On Python 3, / always does proper floating point division, meaning that you always get a float back, you can use // to restore the old behaviour 在Python 3上, /总是进行正确的浮点除法,这意味着您总是会返回float ,可以使用//恢复旧的行为

1 / 2       # gives 0.5
(-1) / 2    # gives -0.5

1 // 2      # gives 0
(-1) // 2   # gives -1

Edited to add: 编辑添加:

Since you are on Python 2.7 (see the edited question), it indeed seems to be the integer division thing you are stuck at. 由于您使用的是python 2.7(请参阅已编辑的问题),因此确实确实是您遇到的整数除法问题。 To get the new Python 3-style behaviour in Python 2, you can also run 要在Python 2中获得新的Python 3样式行为,您还可以运行

from __future__ import division

at the beginning of your program (it must be at the very start, or the interpreter will complain) 在程序的开始 (必须在开始时,否则解释器会抱怨)

Yet another edit regarding int(something) 关于int(something)另一种编辑

Beware that while integer division rounds down , conversion to integer rounds towards zero , like integer division in C++. 要注意的是虽然整数除法向下舍入,转换为整数轮朝向零 ,象整数除法在C ++中。

There are only two major differences between Python / and C++ / . Python /和C ++ /之间只有两个主要区别。

First, for negative numbers, Python rounds toward negative infinity; 首先,对于负数,Python会向负无穷大四舍五入; C++ rounds toward 0. So, -10 / 3 is -4 in Python, -3 (usually) in C++. C ++取整为0。因此,在Python中, -10 / 3为-4,在C ++中通常为-3。

Second, in Python 3.x, or Python 2.x with from __future__ import division , diving two integers with / gives you a float , so 9 / 3 is 3.0 in Python 3.x, but 3 in C++ or Python 2.x. 第二,在Python 3.x或与Python 2.x的from __future__ import division ,潜水两个整数与/给你一个float ,所以9 / 3是3.0在Python 3.x中,但在3 C ++或Python 2.x的。

So, what if you want C++ style division in Python? 那么,如果要在Python中进行C ++样式划分怎么办? Well, the int function always rounds toward 0, not negative infinity. 好吧, int函数总是四舍五入,而不是负无穷大。 So, if you force it to do floating-point division, then call int on the result, instead of letting it to integer division, you will get the same results as in C++. 因此,如果您强迫它进行浮点除法,然后对结果调用int ,而不是将其进行整数除法,您将获得与C ++中相同的结果。 That's why the code you're linking to uses int(b/(a*1.0)) . 这就是您链接到的代码使用int(b/(a*1.0)) I'm not sure that's the best way to write that (especially without even a comment explaining what the point is), but that's what it's there for. 我不确定这是最好的写法(尤其是没有评论要点的评论),但这就是它的用处。

Meanwhile, if you really want to see why things are different, try running your code in the debugger, or an online visualizer, or just adding print calls at each step in the eval loop. 同时,如果您真的想看看为什么会有所不同,请尝试在调试器或联机可视化程序中运行代码,或者只是在eval循环的每个步骤中添加print调用。 Then you can see exactly at which step things go wrong—what the arguments were, what the output was, and what you expected the output to be. 然后,您可以确切地看到出错的步骤-参数是什么,输出是什么,以及您期望输出是什么。 Then you can reduce the problem to a much simpler one, like: 然后,您可以将问题简化为一个简单得多的问题,例如:

a = 4
b = -13
print(b/a)
print(int(b/(a*1.0)))

And then to figure out why those are different, break the int(b/(a*1.0)) down into steps: 然后要弄清楚为什么它们不同,将int(b/(a*1.0))分解为几个步骤:

print(a*1.0)
print(b/(a*1.0))
print(int(b/(a*1.0)))

In C++ if you divide two integer numbers, you get an integer, rounded towards zero. 在C ++中,如果将两个整数相除,则会得到一个整数,四舍五入为零。 For example, 例如,

1 / 2 = 0
-1 / 2 = 0

But if at least one of the arguments is floating point, the result is floating point. 但是,如果至少有一个参数为浮点数,则结果为浮点数。 In python2 for integer arguments / will do integer division, rounded down, for example 在python2中,对于整数参数/将进行整数除法,例如四舍五入

1 / 2 = 0
-1 / 2 = -1

In python3 they changed the behavior of /, and not it always does floating point division 在python3中,他们更改了/的行为,但并非总是进行浮点除法

1 / 2 = 0.5

If you want integer division in python3, you can use // operator 如果要在python3中进行整数除法,可以使用//运算符

1 // 2 = 0
-1 // 2 = -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM