C,Python的 - 不同的行为模的(%)经营 [英] C,Python - different behaviour of the modulo (%) operation
本文介绍了C,Python的 - 不同的行为模的(%)经营的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经发现,在同一模操作取决于正在使用什么语言产生不同的结果。
在Python的:
-1%10
产生 9
在C中,它产生的 1 !
1),哪一个是正确的模?结果
2)如何使mod运行在C像在Python中一样吗?
解决方案
- 这两个变量都是正确的,但是在数学(尤其是数论),Python的模是最常用的
- 在C,你做的
((N%M)+ M)%M
来得到相同的结果在Python。 E.克(( - 1%10)+ 10)%10
。注意,如何它仍然有效为正整数:((17%10)+ 10)%10 == 17%10
,以及为C实现的两个变体(正或负的余数)。
I have found that the same mod operation produces different results depending on what language is being used.
In Python:
-1 % 10
produces 9
In C it produces -1 !
1) Which one is the right modulo?
2) How to make mod operation in C to be the same like in Python?
解决方案
- 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屋!
查看全文