c语言:4种方法;交换两个整数的位置(包括引入第三方变量和不引入第三方变量)
程序:
#include <stdio.h>
void swap(int *p1,int *p2)
{
int t=*p1;
*p1=*p2;
*p2=t;
}
int main()
{
int num1=2;
int num2=4;
int tmp=0;
printf("num1=%d\n",num1);
printf("num2=%d\n",num2);
swap(&num1,&num2);
printf("num1=%d\n",num1);
printf("num2=%d\n",num2);
return 0;
}
结果:
num1=2
num2=4
num1=4
num2=2
Press any key to continue
方法二:异或法
程序:
#include <stdio.h>
int main()
{
int num1=2;
int num2=4;
printf("num1=%d\n",num1);
printf("num2=%d\n",num2);
//num1^num2;
//011
//101
//110
//异或法可以完成对整型变量的交换,对于浮点型变量它无法完成交换
num1 = num1^num2;
num2 = num1^num2;
num1 = num1^num2;
printf("num1=%d\n",num1);
printf("num2=%d\n",num2);
return 0;
}
结果:
num1=2
num2=4
num1=4
num2=2
Press any key to continue
方法三:加减
程序:
#include <stdio.h>
int main()
{
int num1=3;
int num2=12;
printf("num1=%d\n",num1);
printf("num2=%d\n",num2);
num1 = num1+num2;
num2 = num1-num2;
num1 = num1-num2;
//可以交换整型和浮点型数值的变量,但在处理浮点型的时候有可能出现精度的损失
printf("num1=%d\n",num1);
printf("num2=%d\n",num2);
return 0;
}
结果:
num1=3
num2=12
num1=12
num2=3
Press any key to continue
精度损失:
程序:
#include <stdio.h>
int main()
{
float num1=3.123456;
float num2=1234567.000000;
printf("num1=%f\n",num1);
printf("num2=%f\n",num2);
num1 = num1+num2;
num2 = num1-num2;
num1 = num1-num2;
//可以交换整型和浮点型数值的变量,但在处理浮点型的时候有可能出现精度的损失
printf("num1=%f\n",num1);
printf("num2=%f\n",num2);
return 0;
}
结果报错:
num1=3.123456
num2=1234567.000000
num1=1234567.001544
num2=3.123456
Press any key to continue
修改为双精度型double,范围加大,运行结果正确:
num1=3.123456
num2=1234567.000000
num1=1234567.000000
num2=3.123456
Press any key to continue
方法四:乘除
程序:
#include <stdio.h>
int main()
{
int num1=2;
int num2=4;
printf("num1=%d\n",num1);
printf("num2=%d\n",num2);
//同加减法一样,可以交换整型和浮点型数值的变量,但在处理浮点型的时候有可能出现精度的损失
num1 = num1*num2;
num2 = num1/num2;
num1 = num1/num2;
printf("num1=%d\n",num1);
printf("num2=%d\n",num2);
return 0;
}
结果:
num1=2
num2=4
num1=4
num2=2
上一篇: 双沟珍宝坊价格是多少
下一篇: PHP安全配置优化详解