方法一:
创建临时变量
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 1, b = 2;
int temp = a;//创建临时变量temp
a = b;
b = temp;
printf("a=%d,b=%d", a, b);
system("pause");
return 0;
}方法二:
通过异或
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 1, b = 2;
a = a^b;
b = b^a;
a = a^b;
printf("a=%d,b=%d", a, b);
system("pause");
return 0;
}方法三:
通过加减(或乘除)
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 1, b = 2;
a = a + b;//a=a-b也可以
b = a - b;
a = a - b;
printf("a=%d,b=%d", a, b);
system("pause");
return 0;
}方法四:
利用指针交换两个变量的值
#include<stdio.h>
#include<stdlib.h>
void swap(int *p1, int *p2)
{
char temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
int a = 1, b = 2;
swap(&a, &b);
printf("a=%d,b=%d", a, b);
system("pause");
return 0;
}本文出自 “小灰灰” 博客,请务必保留此出处http://10742910.blog.51cto.com/10732910/1719454
原文:http://10742910.blog.51cto.com/10732910/1719454