python和c语言的对比_类C语言与Python负数除法求值间的差异
一直用Python做計算器用(有點大材小用了啊,呵呵)。今天使用時,卻發(fā)現(xiàn)一個詭異的現(xiàn)象,在C語言入門經典(第4版)說正負數(shù)除數(shù)取余操作的差別,就在Python上試驗了一下,結果結成了完全不一樣。下面列出三種語言做同樣運算的差別(外加上Java)。
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:
C代碼 ?
#include?
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:
Python代碼 ?
(
"45/-7="
,
45
/-
7
);
(
"divmod(45,-7)="
,divmod(
45
,-
7
));
(
"45%-7="
,
45
%-
7
);
(
"-45/7="
,-
45
/
7
);
(
"divmod(-45,7)="
,divmod(-
45
,
7
));
(
"-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
可以看到當有負數(shù)存在時,C語言和Python運算的結果是不一樣的。C語言不管正負,結果的絕對值是相等的,而Python卻不一樣。
基于上面的結果,有一個假設,Python取余運算所取的商數(shù)是不大于實際商的最大整數(shù)。即divmod(-45,7)==(math.floor(-45/7),-45%7)。
1
頂
0
踩
分享到:
2011-06-05 21:24
瀏覽 979
評論
總結
以上是生活随笔為你收集整理的python和c语言的对比_类C语言与Python负数除法求值间的差异的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vscode 在标签的src引入别名路径
- 下一篇: jpa 不自动建表_如何来实现Sprin