简体   繁体   English

Python和C ++为-1/2返回不同的值

[英]Python and C++ return different values for -1/2

If I run python on my terminal and type this, and hit enter: 如果我在终端上运行python并键入它,然后按Enter:

-1 / 2

It returns 它返回

-1

If I do the same in XCode, compiling C++ code, and I have this: 如果我在XCode中做同样的事情,则编译C ++代码,并且我有这个:

int idx = -1 / 2;
cout << idx << endl;

It prints this: 它打印此:

0

Why are these rounding differently? 为什么这些舍入方式不同?

EDIT :forgot to mention that 'int' is an integer type (int). 编辑:忘了提到'int'是一个整数类型(int)。 This is corrected. 这已得到纠正。

In Python integer division has always rounded downwards, as if you used the floor function. 在Python中,整数除法始终向下舍入,就像使用了floor函数一样。

In C++03 the rounding direction was left to the compiler. 在C ++ 03中,舍入方向留给编译器。

In C++11 and later it is required to be towards zero. 在C ++ 11和更高版本中,要求接近零。


As I see it, the C++ rounding direction is more easy to understand for novices, since it gives the same kind of numerical result that you would calculate by hand. 正如我所看到的,对于新手来说,C ++取整方向更容易理解,因为它提供了与手工计算相同的数值结果。 It also corresponds to how most computers implement integer division, ie is efficient at the level of individual operations. 它还与大多数计算机如何实现整数除法相对应,即在单个操作级别上是有效的。 The Python rounding direction, on the other hand, is mathematically more elegant and more practically useful in programming. 另一方面,Python的舍入方向在数学上更优雅,在编程中更实用。


One practical difference, illustrating the Pythonic elegance, is to compute how many cabs with capacity of 3 passengers you need for a party of 10 persons. 一个实际的不同是显示Python的优雅之处,它是计算10人聚会所需的载客量为3位乘客的出租车。 In Python, -(-10//3) . 在Python中, -(-10//3) In C++, (10 + (3-1))/3 . 在C ++中, (10 + (3-1))/3

因为这是在这些语言中指定整数除法的方式(向下与向零)。

Python will round any division between integers downwards (ie the smallest of the two integers between the real decimal value). Python会将整数之间的任何除法向下舍入(即,实际十进制值之间的两个整数中的最小值)。 If the result is 2.6, it will round to 2, and if it's -2.6 it will round to -3. 如果结果为2.6,则将舍入为2,如果为-2.6,则将舍入为-3。

C++ will round towards zero (whether the result is positive or negative). C ++将舍入为零(无论结果是正数还是负数)。 So if the result is 2.6 it will be rounded to 2, and if it's -2.6 it will be rounded to -2. 因此,如果结果为2.6,则将四舍五入为2;如果结果为-2.6,则将四舍五入为-2。

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

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