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

前端 未结 3 1317
梦如初夏
梦如初夏 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 09:55

    It seems like a misnomer to me to call it "modulus" and not "remainder" (In math, the answer really should be 9).

    C calls it the % operator, and calls its result the remainder. C++ copies this from C. Neither language calls it the modulus operator. This also explains why the remainder is negative: because the / operator truncates towards 0, and (a / b) * b + (a % b) should equal a.

    Edit: David Rodríguez rightly points out that C++ does define a template class std::modulus, which calls operator%. In my opinion, that class is poorly named. Digging a little bit, it is inherited from STL where it was already named as it is now. The download for STL says "The STL was developed on SGI MIPSproTM C++ 7.0, 7.1, 7.2, and 7.2.1.", and as far as I can tell without actually having the compiler and hardware, MIPSpro passes the division to the CPU and MIPS hardware truncates to 0, which would mean std::modulus has always been misnamed.

提交回复
热议问题