编程实现两个正整数的除法,当然不能用除法操作符

#include<stdio.h>


int div(const int x,const int y){
    return x/y;
}

//位移,效率高
int myDiv(const int x,const int y){
    
    int tmpY = y;
    int dividend = x;
    int result = 0;
    while( dividend >= y ){
        int lsCount = 0; //left shift counter
        while( tmpY <= (dividend >> 1) ){
            tmpY = tmpY << 1;
            lsCount++;
        }
        result += (1 << lsCount);
        printf("%d\n",result);
        tmpY = y;
        dividend -= (y << lsCount);
    }
    

    return result;
}

//用减法,效率低
int myDiv2(const int x,const int y){
    int dividend = x;
    int result = 0;
    while(dividend >= y){
        dividend -= y;
        result++;
    }
    return result;
}



int main()
{
    int x,y;

    printf("int size: %d\n",sizeof(int));

    scanf("%d", &x);
    scanf("%d", &y);
    
    printf("%d / %d = %d\n",x,y,myDiv(x,y));
    printf("%d / %d = %d\n",x,y,myDiv2(x,y));
    printf("%d / %d = %d\n",x,y,div(x,y));
    getchar();

    return 0;
}

posted @ 2012-10-17 10:58  林间走寸  阅读(328)  评论(0)    收藏  举报