C 和 Python

编程入门 行业动态 更新时间:2024-10-19 10:22:31
本文介绍了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 !

  • 哪个是正确的模数?
  • 如何使 C 中的 mod 操作与 Python 中的相同?
  • 推荐答案

  • 两种变体都是正确的,但是在数学(尤其是数论)中,Python 的 modulo 是最常用.
  • 在 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

    本文发布于:2023-11-15 23:29:06,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1598916.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:Python

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!