C 和 Python - 模 (%) 运算的不同行为 [英] C and Python - different behaviour of the modulo (%) operation

查看:43
本文介绍了C 和 Python - 模 (%) 运算的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现相同的 mod 操作会根据使用的语言产生不同的结果.

I have found that the same mod operation produces different results depending on what language is being used.

在 Python 中:

In Python:

-1 % 10

产生9

在 C 中它产生 -1 !

In C it produces -1 !

  1. 哪个是正确的模数?
  2. 如何使 C 中的 mod 操作与 Python 中的相同?

推荐答案

  1. 两种变体都是正确的,但是在数学(尤其是数论)中,Python 的 modulo 是最常用.
  2. 在 C 中,您执行 ((n % M) + M) % M 以获得与 Python 中相同的结果.例如((-1 % 10) + 10) % 10.请注意,它对于正整数仍然有效:((17 % 10) + 10) % 10 == 17 % 10,以及 C 实现的两种变体(正余数或负余数).
  1. Both variants are correct, however in mathematics (number theory in particular), Python's modulo is most commonly used.
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆