实现两个数字的交换
方法1.引入中间变量
#include<stdio.h>
#include <stdlib.h>
int main(){
int a = 10;
int b = 20;
int tep;
printf("交换前的数:a=%d b=%d\n ",a,b);
tep = a;
a = b;
b = tep;
printf("交换后的数:a=%d b=%d\n",a,b);
system("pause");
return 0;
}
方法2.未引入中间变量(按位异或实现)
#include<stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int a = 10;
int b = 20;
printf("交换前的数:a=%d b=%d\n ", a, b);
//进行按位异或
a = a^b;
b = a^b;
a = a^b;
printf("交换后的数字:a=%d b=%d\n", a, b);
system("pause");
return 0;
}
方法3.未引入中间变量(加减)
#include<stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int a = 10;
int b = 20;
printf("交换前的数:a=%d b=%d\n ", a, b);
a = a + b;//30 10
b = a - b;//30 20
a = a - b;//10 20
printf("交换后的数:a=%d b=%d\n", a, b);
system("pause");
return 0;
}
方法4.传指针
#include <stdio.h>
#include <stdlib.h>
void Swap(int* a,int* b){ //
int tep;
tep = *a;
*a = *b;
*b = tep;
}
int main(){
int x= 10;
int y = 20;
printf("交换之前的数:x=%d x=%d\n",x,y);
Swap(&x,&y);
printf("交换之后的数:x=%d y=%d\n",x,y);
system("pause");
return 0;
}
运行结果: