C语言练习篇-2交换两个变量的值

练习:交换两个变量的值。

方法一:中间变量

#include 
int main()
{
    int a=10;
    int b=4;
    printf("a=%d,b=%d\n",a,b);

    //定义一个中间变量来完成两个变量之间的交换
    int temp;
    temp=a;
    a=b;
    b=temp;

    printf("a=%d,b=%d\n",a,b);
    return 0;
}

方法二:宏定义

#include

// 定义一个交换两个数的宏
#define SWAP(x,y,temp) ((temp) = (x),(x) = (y),(y) = (temp))
int main()
{
    int a=10;
    int b=4;
    printf("a=%d,b=%d\n",a,b);

    int temp;
    SWAP(a, b, temp);

    printf("a=%d,b=%d\n",a,b);
    return 0;
}

方法三:算术运算

#include
int main()
{
    int a=10;
    int b=4;
    printf("a=%d,b=%d\n",a,b);

    a=b-a;//a=-6
    b=b-a;//b=10
    a=a+b;//a=4

    printf("a=%d,b=%d\n",a,b);
    return 0;
}

方法四:位运算

#include
int main()
{
    int a=10;
    int b=4;
    printf("a=%d,b=%d\n",a,b);

    a = a^b;
    b = b^a;//b = b^a^b = a
    a = a^b;

    printf("a=%d,b=%d\n",a,b);
    return 0;
}

你可能感兴趣的:(C语言练习篇)