交换两个数的3种方法:宏定义,直接,函数调用

1.不调用函数法:建立临时变量交换

直接在需要处

int temp=b;    b=a;    a=temp;


2。宏定义法:加减法、需要时时有括号 a=a+b b=a-b a=a-b

#define swap(a,b) ((a)=(a)+(b);(b)=(a)-(b);(a)=(a)-(b))

缺点:a+b可能会溢出

3.函数法:

I.指针的方法

     void swap(int *_x,int *_y) //主函数中把两个数的地址传过来
    {
              int  tmp = *_x;    //定义中间变量 然后交换两个数
                *_x = *_y;
                *_y = tmp;
      

    }


II.异或的方法

                             int Swap3(int *a, int *b)
                            {
                                *a = *a^*b;
                                *b = *a^*b;
                                *a = *a^*b;
                                printf("%d %d", *a, *b);
                                return 0;

                             }

   




猜你喜欢

转载自blog.csdn.net/qq1518572311/article/details/80055547