developer tip

C ++ 정수 나누기와 나머지를 얻는 가장 좋은 방법

optionbox 2020. 9. 5. 09:45
반응형

C ++ 정수 나누기와 나머지를 얻는 가장 좋은 방법


a를 b로 나누고 결과 c와 나머지 모두에 관심이 있는지 궁금합니다 (예 : 초 수를 가지고 있고이를 분과 초로 나누고 싶다고 가정 해 보겠습니다). 가장 좋은 방법은 무엇입니까? 그것에 대해?

일 것이다

int c = (int)a / b;
int d = a % b;

또는

int c = (int)a / b;
int d = a - b * c;

또는

double tmp = a / b;
int c = (int)tmp;
int d = (int)(0.5+(tmp-c)*b);

또는

한 번에 둘 다주는 마법의 기능이 있을까요?


x86에서 나머지는 부서 자체의 부산물이므로 반 정도의 컴파일러는 그것을 사용할 수 있어야합니다 ( div다시 수행하지 않음 ). 이것은 아마도 다른 아키텍처에서도 수행 될 것입니다.

지시 : DIVsrc

참고 : 부호없는 나누기. 누산기 (AX)를 "src"로 나눕니다. 제수가 바이트 값이면 결과는 AL에 배치 되고 나머지는 AH에 배치 됩니다. 제수가 워드 값이면 DX : AX를 "src"로 나누고 결과는 AX에 저장 되고 나머지는 DX에 저장됩니다 .

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

std::div 결과와 나머지가 모두있는 구조를 반환합니다.


적어도 x86에서 g ++ 4.6.1은 IDIVL을 사용하고 단일 명령어에서 둘 다 가져옵니다.

C ++ 코드 :

void foo(int a, int b, int* c, int* d)
{
  *c = a / b;
  *d = a % b;
}

x86 코드 :

__Z3fooiiPiS_:
LFB4:
    movq    %rdx, %r8
    movl    %edi, %edx
    movl    %edi, %eax
    sarl    $31, %edx
    idivl   %esi
    movl    %eax, (%r8)
    movl    %edx, (%rcx)
    ret

div () 및 결합 된 division 및 mod를 테스트하는 샘플 코드. 나는 이것을 gcc -O3로 컴파일했고, 컴파일러가 모든 것을 최적화하는 것을 막기 위해 doNothing에 대한 호출을 추가해야했다 (나눗셈 + 모드 솔루션의 경우 출력은 0이 될 것이다).

소금 한 알과 함께 가져 가십시오.

#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);
}

출력 : 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);
}

출력 : 25


In addition to the aforementioned std::div family of functions, there is also the std::remquo family of functions, return the rem-ainder and getting the quo-tient via a passed-in pointer.

[Edit:] It looks like std::remquo doesn't really return the quotient after all.


All else being equal, the best solution is one that clearly expresses your intent. So:

int totalSeconds = 453;
int minutes = totalSeconds / 60;
int remainingSeconds = totalSeconds % 60;

is probably the best of the three options you presented. As noted in other answers however, the div method will calculate both values for you at once.


You cannot trust g++ 4.6.3 here with 64 bit integers on a 32 bit intel platform. a/b is computed by a call to divdi3 and a%b is computed by a call to moddi3. I can even come up with an example that computes a/b and a-b*(a/b) with these calls. So I use c=a/b and a-b*c.

The div method gives a call to a function which computes the div structure, but a function call seems inefficient on platforms which have hardware support for the integral type (i.e. 64 bit integers on 64 bit intel/amd platforms).


You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.

참고URL : https://stackoverflow.com/questions/7070346/c-best-way-to-get-integer-division-and-remainder

반응형