Why is operator% referred to as the “modulus” operator instead of the “remainder” operator?

前端 未结 3 1332
梦如初夏
梦如初夏 2020-12-17 09:36

Today at work I had an interesting discussion with one of my coworkers. He was surprised when he had the following happen to him:



        
3条回答
  •  暖寄归人
    2020-12-17 10:04

    I'm afraid that the problem arises from a misunderstanding of mathematics. Congruence modulo n is an equivalence relation, so it only defines equivalence classes. Hence, it's not correct to say that 'in math, the answer really should be 9' because it could be as well 19, 29, and so forth. And of course it can be -1 or -11. There are infinite elements of the class of the numbers n that are n ≡ -1 mod(10).

    http://en.wikipedia.org/wiki/Modular_arithmetic

    http://en.wikipedia.org/wiki/Congruence_relation

    So, the correct question could be: which element of the class of the numbers that are ≡ -1 mod(10) will be the result of -1 % 10 in C++? And the answer is: the remainder of the division of -1 by 10. No mystery.

    PS Your definition of modulus and Knuth's are, ehm, equivalent...:)

提交回复
热议问题