C++ Best way to get integer division and remainder

后端 未结 8 1948
挽巷
挽巷 2020-12-01 00:29

I am just wondering, if I want to divide a by b, and am interested both in the result c and the remainder (e.g. say I have number of seconds and want to split that into minu

8条回答
  •  心在旅途
    2020-12-01 00:56

    On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div again). This is probably done on other architectures too.

    Instruction: DIV src

    Note: Unsigned division. Divides accumulator (AX) by "src". If divisor is a byte value, result is put to AL and remainder to AH. If divisor is a word value, then DX:AX is divided by "src" and result is stored in AX and remainder is stored in DX.

    int c = (int)a / b;
    int d = a % b; /* Likely uses the result of the division. */
    

提交回复
热议问题