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