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

前端 未结 3 1341
梦如初夏
梦如初夏 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

    % is the remainder operator in C and C++.

    In the C++ Standard, it is called the %operator and it yields the the remainder from the division. In the C Standard it is called the % operator and since C99 it is actually a remainder operator. The modulo and remainder operators differ with respect to negative values.

    The % operator is defined in C and C++ with a == (a / b * b) + a % b.

    Truncation of the integer division towards 0 in C is done since C99. In C89 it was implementation defined (and % can be a modulo operator in C89). C++ also performs truncation towards zero for integer division.

    When truncation is done towards zero, % is a remainder operator and the sign of the result is the sign of the dividend. When truncation is done towards minus infinity, % is a modulo operator and the sign of the result is the sign of the divisor.

    On the reasons why C changed the implementation defined behavior of the integer division regarding truncation, Doug Gwyn from C comittee said:

    C99 imposed a Fortran-compatible requirement in an attempt to attract more Fortran rogrammers and to aid in converting Fortran code to C.

    C99 Rationale says regarding truncation towards zero integer division:

    In Fortran, however, the result will always truncate toward zero, and the overhead seems to be acceptable to the numeric programming community. Therefore, C99 now requires similar behavior, which should facilitate porting of code from Fortran to C.

    In gcc the implementation behavior in C89 has always been the truncation towards zero.

    So % is the remainder operator in C99, C++ and also in Java but is not the remainder operator in all programming languages. In Ruby and Python, % is in fact the modulo operator (integer division is done towards minus infinity in these languages). Haskhell and Scheme have two separate operators: mod and rem for Haskell, and modulo and remainder for Scheme.

提交回复
热议问题