加法&除法

来源:互联网 发布:ubuntu 系统字体路径 编辑:程序博客网 时间:2024/05/01 11:09
#include <stdio.h>// 除法int div(int loperand, int roperand){    int cnt = 0;    while (loperand > roperand)    {        cnt++;        loperand -= roperand;    }    return cnt;}// 取余数int getRemainder(int loperand, int roperand){    while (loperand > roperand)        loperand -= roperand;    return loperand;}// 加法unsigned int add(unsigned int loperand, unsigned int roperand){    int currentbit = 0, carrybit = 0;    unsigned int res = 0;    int cnt = 0;    int len = sizeof(loperand) << 3;    while (cnt < len)    {        int tmp = carrybit;     // 临时存放进位位        carrybit = 0;        // 计算当前位结果        currentbit = (loperand & 0x01) ^ (roperand & 0x01);        // 判断当前位置计算是否进位        if (currentbit == 0 && (loperand & 0x01) == 1)            carrybit = 1;        else if (currentbit == 1 && tmp == 1)            carrybit = 1;        currentbit ^= tmp;        // 计算结果        res |= (currentbit << cnt);        cnt++;        loperand >>= 1, roperand >>= 1;    }    return res;}int main(){    int num1 = 65535;    int num2 = 65535;    printf("%d + %d = %d", num1, num2, add(num1, num2));    return 0;}

原创粉丝点击