加法&除法

 1 #include <stdio.h>
 2 
 3 // 除法
 4 int div(int loperand, int roperand)
 5 {
 6     int cnt = 0;
 7     while (loperand > roperand)
 8     {
 9         cnt++;
10         loperand -= roperand;
11     }
12 
13     return cnt;
14 }
15 
16 // 取余数
17 int getRemainder(int loperand, int roperand)
18 {
19     while (loperand > roperand)
20         loperand -= roperand;
21 
22     return loperand;
23 }
24 
25 // 加法
26 unsigned int add(unsigned int loperand, unsigned int roperand)
27 {
28     int currentbit = 0, carrybit = 0;
29     unsigned int res = 0;
30     int cnt = 0;
31     int len = sizeof(loperand) << 3;
32 
33     while (cnt < len)
34     {
35         int tmp = carrybit;     // 临时存放进位位
36         carrybit = 0;
37         // 计算当前位结果
38         currentbit = (loperand & 0x01) ^ (roperand & 0x01);
39         // 判断当前位置计算是否进位
40         if (currentbit == 0 && (loperand & 0x01) == 1)
41             carrybit = 1;
42         else if (currentbit == 1 && tmp == 1)
43             carrybit = 1;
44         currentbit ^= tmp;
45         // 计算结果
46         res |= (currentbit << cnt);
47         cnt++;
48         loperand >>= 1, roperand >>= 1;
49     }
50 
51     return res;
52 }
53 int main()
54 {
55     int num1 = 65535;
56     int num2 = 65535;
57 
58     printf("%d + %d = %d", num1, num2, add(num1, num2));
59 
60     return 0;
61 }
posted @ 2013-03-21 18:38  life91  阅读(217)  评论(0编辑  收藏  举报