一直用Python做计算器用(有点大材小用了啊,呵呵)。今天使用时,却发现一个诡异的现象,在C语言入门经典(第4版)说正负数除数取余操作的差别,就在Python上试验了一下,结果结成了完全不一样。下面列出三种语言做同样运算的差别(外加上Java)。
Java:
- import java.lang.*;
- public class divmod
- {
- public static void main(String[] args)
- {
- System.out.println("45/-7=" +( 45 /- 7 ));
- System.out.println("45%-7=" +( 45 %- 7 ));
- System.out.println("-45/7=" +(- 45 / 7 ));
- System.out.println("-45%7=" +(- 45 % 7 ));
- }
- }
结果是:
C:\Documents and Settings\g1309288>cd /d D:\javapro
D:\JavaPro>javac divmod.java
D:\JavaPro>java divmod
45/-7=-6
45%-7=3
-45/7=-6
-45%7=-3
C:
- #include <stdio.h>
- main()
- {
- printf("45/-7=%2d\n" ,45/-7);
- printf("45%%-7=%2d\n" ,45%-7);
- printf("-45/7=%2d\n" ,-45/7);
- printf("-45%%7=%2d\n" ,-45%7);
- }
结果是:
45/-7=-6
45%-7= 3
-45/7=-6
-45%7=-3
Python:
- print ( "45/-7=" , 45 /- 7 );
- print ( "divmod(45,-7)=" ,divmod( 45 ,- 7 ));
- print ( "45%-7=" , 45 %- 7 );
- print ( "-45/7=" ,- 45 / 7 );
- print ( "divmod(-45,7)=" ,divmod(- 45 , 7 ));
- print ( "-45%7=" ,- 45 % 7 );
结果是:
C:\Documents and Settings\g1309288\桌面>divmod.py
45/-7= -6.428571428571429
divmod(45,-7)= (-7, -4)
45%-7= -4
-45/7= -6.428571428571429
divmod(-45,7)= (-7, 4)
-45%7= 4
可以看到当有负数存在时,C语言和Python运算的结果是不一样的。C语言不管正负,结果的绝对值是相等的,而Python却不一样。
基于上面的结果,有一个假设,Python取余运算所取的商数是不大于实际商的最大整数。即divmod(-45,7)==(math.floor(-45/7),-45%7)。