cpu如何计算1+2?

3+2=?

首先,将1,2存入到容器中

x:0010

y:0011

1.cpu首先将两个数进行异或

 x^y   0010

    xor 0011

---------------

          0001

将0001 存入另一个容器R

2.cpu如何确定算完了?(为了确定R是否已经算到最后了)与运算

  x&y    0010

        &  0011

---------------

             0010

然后将 0010 <<1 == 0100,如果全0,R就是结果,如果没有,将

R:0001

x=0001

y=0100;

3.重复第1步骤

        0001

xor   0100

------------

        0101

将结果在放到R中 R:0101

4.重复第二步骤

     0001

&   0100

----------

      0000 ---》说明结果算到了最后,结果就是R:0101 ==5

#include<stdio.h>

int plus(int a,int b)
{
  int x,y;

  if(a==0) return b;
  if(b==0) return a;
    
   x=x^y;
   y=(x&y)<<1; 
   return plus(x,y);
}

int main(void)
{
 printf("%d\n"plus(5,8));
 return 0;
}

 

利用宏定义进行两个参数之间交换

#include<stdio.h>
#define SWAP(a,b)\
  (a)=(a)+(b);\
  (b)=(a)-(b);\
  (a)=(a)-(b);


int main(void)
{
    int a=3,b=4;
    printf("a=%d,b=%d\n",a,b);
    SWAP(a,b);
    printf("a=%d,b=%d\n",a,b);
     
    getchar();
 return 0;
}

 

posted on 2016-04-12 15:24  碎紫妖瞳  阅读(328)  评论(0编辑  收藏  举报

导航