數值變數交換常用方法

2021-09-16 20:09:14 字數 1294 閱讀 7592

echo "\n---臨時變數法---\n";

$num1 = 3;

$num2 = 6;

echo "交換前:\n", '$num1 = ', $num1, "\n", '$num2 = ', $num2, "\n";

$tmp = $num1;

$num1 = $num2;

$num2 = $tmp;

echo "交換後:\n", '$num1 = ', $num1, "\n", '$num2 = ', $num2, "\n";

/*---臨時變數法---

交換前:

$num1 = 3

$num2 = 6

交換後:

$num1 = 6

$num2 = 3

*/

echo "\n---加減法---\n";

$num1 = 3;

$num2 = 6;

echo "交換前:\n", '$num1 = ', $num1, "\n", '$num2 = ', $num2, "\n";

$num1 = $num1 + $num2;

$num2 = $num1 - $num2;

$num1 = $num1 - $num2;

echo "交換後:\n", '$num1 = ', $num1, "\n", '$num2 = ', $num2, "\n";

/*---加減法---

交換前:

$num1 = 3

$num2 = 6

交換後:

$num1 = 6

$num2 = 3

*/

echo "\n---異或法---\n";

$num1 = 3;

$num2 = 6;

echo "交換前:\n", '$num1 = ', $num1, "\n", '$num2 = ', $num2, "\n";

$num1 = $num1 ^ $num2;

$num2 = $num1 ^ $num2;

$num1 = $num1 ^ $num2;

echo "交換後:\n", '$num1 = ', $num1, "\n", '$num2 = ', $num2, "\n";

/*---異或法---

交換前:

$num1 = 3

$num2 = 6

交換後:

$num1 = 6

$num2 = 3

*/

交換變數方法

1.第一種寫法 建議使用這種最好 1 int temp num1 2 num1 num2 3 num2 temp 2.第二種寫法 1 num1 num1 num2 2 num2 num1 num2 3 num1 num1 num2 3.第三種寫法 1 num1 num1 num2 2 num2 nu...

通過異或交換變數的數值

通過異或交換變數的數值,最我最為推薦的swap方法,相比 借用第三變數,temp a a b b temp 異或交換 更有效率!利用加減法,a a b b a b a a b 異或交換 適用範圍更廣。這裡的適用範圍更廣,說得有點牽強。加減法給我的直觀感覺是 不安全,當 a a b 的結果超出了該變數...

交換變數(簡便方法)

variable1 input 請輸入第乙個變數 variable2 input 請輸入第二個變數 variable3 variable2 variable2 variable1 variable1 variable3 print 第乙個變數是 variable1 print 第二個變數是 vari...