ホームページ  >  に質問  >  本文

python - 7除-3的商和余数分别是多少?

python2里 7/-3得-3,7%-3得-2 而C里,7/-3得-2,7%-3得1

伊谢尔伦伊谢尔伦2741日前2241

全員に返信(3)返信します

  • 大家讲道理

    大家讲道理2017-04-17 11:27:15

    python2里的7/-3先是等于-2.3333333333333335,然后按照向下取整为-3,然后按照余数的定义计算7%-3,即7 - ( -3* -3)= -2. C里(7/-3)是直接扔掉整数位后的位所以为-2,-2 * -3 = 6,7-6=1. python3改变了这个操作符的行为,7/-3 = -2.3333333333333335。 都没有错,只不过取整的方法不一样。

    python2里可以

    from __future__ import pision
    

    然后行为就跟python3一样了。

    原因

    返事
    0
  • 黄舟

    黄舟2017-04-17 11:27:15

    这取决于程序语言设计者对除法、余数运算的定义。

    Oberon07语言规定:

    The operators p and MOD apply to integer operands only. Let q = x p y, and r = x MOD y. Then quotient q and remainder r are defined by the equation

    x = q*y + r     0 <= r < y 
    

    这就使得7 p (-3) = -2、7 MOD (-3) = 1;(-7) p 3 = -3、(-7) MOD 3 = 2。

    C语言规定:

    When integers are pided, the result of the / operator is the algebraic quotient with any fractional part discarded.
    This is often called ''truncation toward zero''.

    If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined.

    这就使得 7 / (-3) == -2、7 % (-3) == 1;(-7) / 3 == -2、(-7) % 3 == -1。

    返事
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 11:27:15

    python语言里整除默认为向下取整,c系列语言里整除默认为向零取整。是这个原因把。C语言里还规定了A%B的值与A符号一致。

    返事
    0
  • キャンセル返事