本文介绍了为什么在C ++中将-1/2评估为0,而在Python中将-1评估为-1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • C ++ cout<< -1/2 的计算结果为 0

  • Python -1/2 的值为 -1

  • C++: cout << -1/2 evaluates to 0
  • Python: -1/2 evaluates to -1.

为什么会这样?

推荐答案

C ++中的整数除法会舍入为0,而在Python中则舍入为整数

Integer division in C++ rounds toward 0, and in Python, it rounds toward -infinity.

抽象地处理这些问题的人们倾向于感觉绕向负无穷大更有意义(这意味着它与定义于数学,而不是的意思)。编程语言的传统是四舍五入-最初不是在C ++中定义的(当时是按照C的示例),但是最终C ++(和C)以这种方式定义了它,复制了Fortran。

People dealing with these things in the abstract tend to feel that rouding toward negative infinity makes more sense (that means it's compatible with the modulo function as defined in mathematics, rather than % having a somewhat funny meaning). The tradition in programming languages is to round toward 0--this wasn't originally defined in C++ (following C's example at the time), but eventually C++ (and C) defined it this way, copying Fortran.

这篇关于为什么在C ++中将-1/2评估为0,而在Python中将-1评估为-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:26