zoukankan      html  css  js  c++  java
  • 加法&除法

     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 }
  • 相关阅读:
    一个Fragment的实例
    使用LayoutInflater添加一个布局引用
    11F:42点
    11E:分形盒
    11D:猴子摘桃
    11C:寻找边缘
    11B:夺宝探险
    10J:判断整除
    11A:篮球联赛
    10I:核电站
  • 原文地址:https://www.cnblogs.com/life91/p/2973992.html
Copyright © 2011-2022 走看看