C++ Best way to get integer division and remainder

后端 未结 8 1891
挽巷
挽巷 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 01:11

    std::div returns a structure with both result and remainder.

    0 讨论(0)
  • 2020-12-01 01:13

    Sample code testing div() and combined division & mod. I compiled these with gcc -O3, I had to add the call to doNothing to stop the compiler from optimising everything out (output would be 0 for the division + mod solution).

    Take it with a grain of salt:

    #include <stdio.h>
    #include <sys/time.h>
    #include <stdlib.h>
    
    extern doNothing(int,int); // Empty function in another compilation unit
    
    int main() {
        int i;
        struct timeval timeval;
        struct timeval timeval2;
        div_t result;
        gettimeofday(&timeval,NULL);
        for (i = 0; i < 1000; ++i) {
            result = div(i,3);
            doNothing(result.quot,result.rem);
        }
        gettimeofday(&timeval2,NULL);
        printf("%d",timeval2.tv_usec - timeval.tv_usec);
    }
    

    Outputs: 150

    #include <stdio.h>
    #include <sys/time.h>
    #include <stdlib.h>
    
    extern doNothing(int,int); // Empty function in another compilation unit
    
    int main() {
        int i;
        struct timeval timeval;
        struct timeval timeval2;
        int dividend;
        int rem;
        gettimeofday(&timeval,NULL);
        for (i = 0; i < 1000; ++i) {
            dividend = i / 3;
            rem = i % 3;
            doNothing(dividend,rem);
        }
        gettimeofday(&timeval2,NULL);
        printf("%d",timeval2.tv_usec - timeval.tv_usec);
    }
    

    Outputs: 25

    0 讨论(0)
提交回复
热议问题