一、借用一个临时变量交换两个变量值
public class test {
public static void main(String[] args) {
int a = 2;
int b = 4;
int temp;//申请一个临时变量
System.out.println(a + " " + b);
temp = a;
a = b;
b = temp;
System.out.println(a + " " + b);
}
}
运行结果如下:
二、不用临时变量,交换两个变量值
public class test {
public static void main(String[] args) {
//虽然不用借用临时变量,但是这种计算可能会导致越界
int a = 6;
int b = 4;
System.out.println(a+" "+b);
//方法一
//a = b - a; //a = 6 - 4 = 2
//b = b - a; //b = 6 - 2 = 4
//a = b + a; //a = 4 + 2 = 6
//方法二
a = a + b; //a = 6 + 4 = 10
b = a - b; //b = 10 - 4 = 6
a = a - b; //a = 4 + 2 = 6
System.out.println(a+" "+b);
}
}
运行结果如下:
三、用指针交换两个变量值
#include<stdio.h>
int main()
{
int a = 6;
int b = 4;
int temp;
int *p1 = &a;
int *p2 = &b;
printf("a和b的值为%d %d\n", a, b);
printf("*p1和*p2的值为%d %d\n", *p1, *p2);
temp = *p1;
*p1 = *p2;
*p2 = temp;
printf("a和b的值为%d %d\n", a, b);
printf("*p1和*p2的值为%d %d\n", *p1, *p2);
return 0;
}
运行结果如下: