C和Python-模(%)操作的不同行为 [英] C and Python - different behaviour of the modulo (%) operation
本文介绍了C和Python-模(%)操作的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现根据使用的语言,相同的mod操作会产生不同的结果.
I have found that the same mod operation produces different results depending on what language is being used.
在Python中:
-1 % 10
产生 9
在C语言中,它生成 -1 !
- 哪个是正确的模?
- 如何使C中的mod操作与Python中的一样?
推荐答案
- 两个变体都是正确的,但是在数学(尤其是数论)中,Python的取模是最常用的.
- 在C中,您执行
((n % M) + M) % M
可获得与Python中相同的结果.例如((-1 % 10) + 10) % 10
.请注意,它仍然对正整数((17 % 10) + 10) % 10 == 17 % 10
以及C实现的两种变体(正或负余数)仍然有效.
- Both variants are correct, however in mathematics (number theory in particular), Python's modulo is most commonly used.
- In C, you do
((n % M) + M) % M
to get the same result as in Python. E. g.((-1 % 10) + 10) % 10
. Note, how it still works for positive integers:((17 % 10) + 10) % 10 == 17 % 10
, as well as for both variants of C implementations (positive or negative remainder).
这篇关于C和Python-模(%)操作的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文