3
30
2013
74

负整数的整除和取余运算

负整数间是怎么整除和取余数的呢?

数学上貌似没定义,但计算机确实能算。于是就试了试,想总结一下规律。

一不小心发现,C/C++ 和 Python 下的结果是不同的:

  C/C++ Python 精确值
-14/3 -4 -5 -4.67
-14%3 -2 1 /
14/-3 -4 -5 -4.67
14%-3 2 -1 /
-14/-3 4 4 4.67
-14%-3 -2 -2 /

总结规律如下:

  1. 两种语言中,商和余数都符合 被除数=商x除数+余数 这一数学规律。
  2. 两种语言中,整除的方法不同:C/C++ 是向零取整(负数向上、正数向下取整),Python 是下取整

 

以 n/3 和 n%3 为例,看看这两种处理方法的区别。

C 的情况,两种运算结果都关于0对称和反号

n -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5
-1 -1 -1 0 0 0 0 0 1 1 1
余数 -2 -1 0 -2 -1 0 1 2 0 1 2

Python 的情况,运算结果是完全连续的:

n -5 -4 -3 -2 -1 0 +1 +2 +3 +4 +5
-2 -2 -1 -1 -1 0 0 0 1 1 1
余数 1 2 0 1 2 0 1 2 0 1 2

不知道那种在数学上更好用。个人觉得 Python 的处理方式更优美一些吧。

 

至于其他语言的处理方法,应该也出不了这两种。我所知道的:

  • C/C++ “向零取整式整除”:C/C++、Java、bash
  • Python “下取整式整除”:Python、Perl、Lua
Category: 计算机 | Tags: python c/c++ 编程 数学 | Read Count: 20199
Avatar_small
endle 说:
2013年4月21日 21:09

刚才无意中看到一篇文章 http://ceeji.net/blog/mod-in-real
在评论里看到,这是两种除法的定义方式。

Avatar_small
比尔盖子 说:
2013年5月07日 17:27

其实不完全正确。在 C99 之前 C 语言的取整是未定义的,不同架构上不同的编译器都可能导致完全不同的结果,而且这个结果多半是在这种硬件上最快的。

Avatar_small
endle 说:
2013年5月08日 09:13

@比尔盖子: 我在K&R的书上看到一段代码,认定C是向零取整的。请问,准确的C语言规范应该在哪里查?谢谢了。

Avatar_small
比尔盖子 说:
2013年5月17日 18:20

C 语言规范请查阅 C89 (ANSI C) 和 C99 的 ISO 文档。K&R 第二版是 ANSI C,有些对于 C99 来说已经不正确了。

C89 中,-22 / 7 = -3, -22 % 7 = -1,也可以-22 / 7= -4, -22 % 7 = 6。 而C99中明确为 -22 / 7 = -3, -22 % 7 = -1,只有一种结果。

Avatar_small
endle 说:
2013年5月19日 08:35

@比尔盖子: 谢谢。我回头去啃文档

Avatar_small
ceclinux 说:
2013年6月08日 18:56

python3有些不同了
cecil@cecil-Aspire-4750:~$ python3
Python 3.2.3 (default, Oct 19 2012, 20:13:42)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> -14/3
-4.666666666666667
>>> -14%3
1

Avatar_small
endle 说:
2013年6月08日 20:09

@ceclinux: python3里,你要写 -14//3
>>> -14//3
-5

Avatar_small
ceclinux 说:
2013年6月08日 20:10

@endle:
初学python,谢谢了

Avatar_small
什么值得买 说:
2013年6月30日 13:27

很基础,总结的不错

Avatar_small
龙腾天下 说:
2013年8月16日 14:42

很多语言都有点相关,但是在运算时总是又有差异。我做app的时候,以常遇到这些问题。思路是很好的

Avatar_small
yousong 说:
2013年9月09日 09:59

这个在Graham & Knuth的"Concrete Mathematics"里有讲过,书里的定义结果是向下取整。记得Guido van Rossum也写过一篇文章讲原因。

a mod b = a - b * floor(a / b)

书中floor(x)的定义本身也为向下(负无穷方向)取整。

Avatar_small
yousong 说:
2013年9月09日 10:03

记错了。

http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html

Avatar_small
韩语 说:
2013年9月29日 17:36

这样算好像有语法错误,中断结果

Avatar_small
Brilliance 说:
2014年1月01日 20:21

两数相除,同号得正,异号得负,并把绝对值相除,0除以任何一个不等于0的数,都得0.
很明显在数学方面来看取整应该是向0的,因为0没有符号.
判断的时候判断模比较符合数学规则,显然pyhon有点问题

Avatar_small
seo service UK 说:
2023年11月01日 18:36

Cool stuff you have and you keep overhaul every one of us

Avatar_small
먹튀없는사이트 说:
2023年11月26日 18:51

The PCSO Lotto Result today and yesterday this October 2023 is here! Refresh page for official winning numbers - 6/58, 6/55, 6/49, 6/45, 6/42, Swertres 

Avatar_small
먹튀검증 说:
2023年11月26日 18:51

Admiring the time and effort you put into your blog and detailed information you offer!.

Avatar_small
스포츠토토사이트 说:
2023年11月26日 18:51

The PCSO Lotto Result today and yesterday this October 2023 is here! Refresh page for official winning numbers - 6/58, 6/55, 6/49, 6/45, 6/42, Swertres 

Avatar_small
먹튀없는사이트 说:
2023年11月26日 18:54

Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

Avatar_small
토토가족방추천 说:
2023年11月26日 18:54

Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info

Avatar_small
토토핫 보증업체 说:
2023年11月26日 18:55

I’ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website.

Avatar_small
다리다리게임방법 说:
2023年11月26日 18:57

Thank you so much as you have been willing to share information as ABC.

Avatar_small
먹튀클래스 说:
2023年11月26日 18:58

Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has the same topic with your article. Thanks, great share 

Avatar_small
W토토사이트 가입코드 说:
2023年11月26日 19:04

I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit

Avatar_small
먹튀사이트 说:
2023年11月26日 19:07

I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.

Avatar_small
그래프게임특징 说:
2023年11月26日 19:11

I basically need to reveal to you that I am new to weblog and certainly enjoyed this blog webpage. Likely I'm going to bookmark your blog . You totally have superb stories. Supports imparting to us your blog.

Avatar_small
가입머니주는사이트 说:
2023年11月26日 19:12

I've found this interesting! Check it out!

Avatar_small
토토사이트코드 说:
2023年11月26日 19:15

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work

Avatar_small
토토사이트 제작 방법 说:
2023年11月26日 19:17

I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit

Avatar_small
메이저안전공원 说:
2023年11月26日 19:19

Awesome Website. Keep up the good work.

Avatar_small
먹튀사이트 说:
2023年11月26日 19:33

Thank you so much as you have been willing to share information with us. We will forever admire all you have done here because you have made my work as easy as ABC.

Avatar_small
토토사이트추천 说:
2023年11月26日 19:34

Every one of the substance you said in post is too great and can be extremely helpful. I will remember it, much obliged for sharing the data continue upgrading, looking forward for more posts.Thanks . Decent to be going to your web

Avatar_small
안전놀이터 说:
2023年11月26日 19:37

I think that thanks for the valuabe information and insights you have so provided here. 

Avatar_small
골드피쉬카지노가입 说:
2023年11月26日 19:43

That appears to be excellent however i am still not too sure that I like it. At any rate will look far more into it and decide personally

Avatar_small
링크모음사이트 说:
2023年11月26日 19:46

Thanks for every other informative site. The place else may just I get that kind of information written in such an ideal means? I have a venture that I’m just now operating on, and I have been on the look out for such information 

Avatar_small
에그벳 说:
2023年11月26日 19:52

Thank you so much as you have been willing to share information with us. We will forever admire all you have done here because you have made my work as easy as ABC.

Avatar_small
사설토토사이트 说:
2023年11月26日 19:52

I've found this interesting! Check it out!

Avatar_small
메이저토토사이트 说:
2023年11月26日 19:59

This is actually the kind of information I have been trying to find. Thank you for writing this information

Avatar_small
메이저놀이터코드 说:
2023年11月26日 20:02

I basically need to reveal to you that I am new to weblog and certainly enjoyed this blog webpage. Likely I'm going to bookmark your blog . You totally have superb stories. Supports imparting to us your blog.

Avatar_small
토토사이트 说:
2023年11月26日 20:10

Awesome Website. Keep up the good work.

Avatar_small
토토사이트 说:
2023年11月26日 20:10

It's always exciting to read articles from other writers and practice something from their web sites 

Avatar_small
먹튀검증사이트 说:
2023年11月26日 20:11

I think this is a really good article. You make this information interesting and engaging. You give readers a lot to think about and I appreciate that kind of writing

Avatar_small
토토사이트 说:
2023年11月26日 20:22

I’m happy I located this blog! From time to time, students want to cognitive the keys of productive literary essays composing. Your first-class knowledge about this good post can become a proper basis for such people. nice one 

Avatar_small
에볼루션카지노 说:
2023年11月26日 20:22

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free

Avatar_small
토토마스터즈역할 说:
2023年11月26日 20:26

Admiring the time and effort you put into your blog and detailed information you offer!.

Avatar_small
사설토토검증 说:
2023年11月26日 20:34

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free

Avatar_small
먹튀검증커뮤니티 说:
2023年11月26日 20:36

Really a great addition. I have read this marvelous post. Thanks for sharing information about it. I really like that 

Avatar_small
꽁머니닷컴주소 说:
2023年11月26日 20:36

I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.

Avatar_small
먹튀솔루션가입 说:
2023年11月26日 20:45

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free

Avatar_small
토토사이트 说:
2023年11月26日 20:55

Thanks for every other informative site. The place else may just I get that kind of information written in such an ideal means? I have a venture that I’m just now operating on, and I have been on the look out for such information 

Avatar_small
먹튀검증업체 说:
2023年11月26日 21:12

I basically need to reveal to you that I am new to weblog and certainly enjoyed this blog webpage. Likely I'm going to bookmark your blog . You totally have superb stories. Supports imparting to us your blog.

Avatar_small
먹튀검증 说:
2024年1月15日 16:43

Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people

Avatar_small
소액결제현금화 说:
2024年1月15日 21:46

This is a truly good site post. Not too many people would actually, the way you just did. I am really impressed that there is so much information about this subject that have been uncovered and you’ve done your best, with so much class. If wanted to know more about green smoke reviews, than by all means come in and check our stuff.

Avatar_small
스포츠중계 说:
2024年1月15日 22:17

this is really good website, coolest I have ever visit thank you so much, i will follow and stay tuned much appriciated

Avatar_small
카지노사이트 说:
2024年1月15日 22:36

I enjoy looking through an article that will make people think. Also, thank you for allowing for me to comment

Avatar_small
바카라사이트 说:
2024年1月16日 14:29

Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice

Avatar_small
카지노사이트추천 说:
2024年1月16日 15:11

I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post

Avatar_small
industrial outdoor s 说:
2024年1月16日 15:28

I simply want to tell you that I am new to weblog and definitely liked this blog site. Very likely I’m going to bookmark your blog . You absolutely have wonderful stories. Cheers for sharing with us your blog.

Avatar_small
먹튀검증 说:
2024年1月16日 15:45

You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming

Avatar_small
카지노 올인토토 说:
2024年1月16日 16:04

I can suggest essentially not too bad and even dependable tips, accordingly see it: 

Avatar_small
카지노뱅크 说:
2024年1月16日 16:47

Acknowledges for paper such a beneficial composition, I stumbled beside your blog besides decipher a limited announce. I want your technique of inscription…

Avatar_small
카지노 커뮤니티 说:
2024年1月18日 14:20

I feel a lot more people need to read this, very good info!

Avatar_small
안전놀이터 说:
2024年1月22日 16:31

온라인 카지노 커뮤니티 온카허브 입니다. 온카허브는 카지노 먹튀 사이트들과 안전한 카지노 사이트 정보를 공유하고 있습니다. 카지노 먹튀검증 전문팀을 자체적으로 운영함으로써 철저한 검증을 진행하고 있습니다.

Avatar_small
메이저사이트 说:
2024年1月22日 16:32

온라인 카지노 커뮤니티 온카허브 입니다. 온카허브는 카지노 먹튀 사이트들과 안전한 카지노 사이트 정보를 공유하고 있습니다. 카지노 먹튀검증 전문팀을 자체적으로 운영함으로써 철저한 검증을 진행하고 있습니다.
https://oncahub24.com/

Avatar_small
바카라 说:
2024年1月24日 11:35

바카라 바카라사이트 우리카지노 카지노는 바카라, 블랙잭, 룰렛 및 슬롯 등 다양한 게임을 즐기실 수 있는 공간입니다. 게임에서 승리하면 큰 환호와 함께 많은 당첨금을 받을 수 있고, 패배하면 아쉬움과 실망을 느끼게 됩니다.

Avatar_small
하노이 밤문화 说:
2024年1月24日 12:13

하노이 꼭 가봐야 할 베스트 업소 추천 안내 및 예약, 하노이 밤문화 에 대해서 정리해 드립니다. 하노이 가라오케, 하노이 마사지, 하노이 풍선바, 하노이 밤문화를 제대로 즐기시기 바랍니다. 하노이 밤문화 베스트 업소 요약 베스트 업소 추천 및 정리.

Avatar_small
먹튀검증 说:
2024年1月25日 14:55

No.1 먹튀검증 사이트, 먹튀사이트, 검증사이트, 토토사이트, 안전사이트, 메이저사이트, 안전놀이터 정보를 제공하고 있습니다. 먹튀해방으로 여러분들의 자산을 지켜 드리겠습니다. 먹튀검증 전문 커뮤니티 먹튀클린만 믿으세요!!

Avatar_small
베트남 밤문화 说:
2024年1月25日 16:14

베트남 남성전용 커뮤니티❣️ 베트남 하이에나 에서 베트남 밤문화를 추천하여 드립니다. 베트남 가라오케, 베트남 VIP마사지, 베트남 이발관, 베트남 황제투어 남자라면 꼭 한번은 경험 해 봐야할 화끈한 밤문화로 모시겠습니다. 

Avatar_small
seo service london 说:
2024年2月22日 18:42

This article is an appealing wealth of informative data that is interesting and well-written

Avatar_small
카지노사이트 说:
2024年4月06日 11:34

온라인 카지노 커뮤니티 온카허브 입니다. 온카허브는 카지노 먹튀 사이트들과 안전한 카지노 사이트 정보를 공유하고 있습니다. 카지노 먹튀검증 전문팀을 자체적으로 운영함으로써 철저한 검증을 진행하고 있습니다

Avatar_small
Cryto exchange 说:
2024年6月03日 12:18

The tech-original mission is to help you better understand technology, and make better decisions in the fields of IT, Tech, and Crypto.
https://www.tech-original.com/

Avatar_small
Cryto exchange 说:
2024年6月07日 17:57

The tech-original mission is to help you better understand technology, and make better decisions in the fields of IT, Tech, and Crypto.
https://www.tech-original.com/


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

| Theme: Aeros 2.0 by TheBuckmaker.com