关于两变量交换代码的原理及a=20、b=10时结果为20的疑问
Hey there! Let's unpack this question step by step. Since you didn't share the exact swap code you're working with, I'll cover the most common variable swap approaches first, then dive into why you might be seeing 20 as a result when a=20 and b=10.
1. Temporary Variable Method (Most Reliable)
This is the straightforward, foolproof way to swap variables—you use a temporary placeholder to avoid overwriting values before you're done with them:
a = 20 b = 10 temp = a # temp holds 20 a = b # a now becomes 10 b = temp # b now becomes 20
After running this, a=10 and b=20—a perfect swap.
2. Arithmetic Swap (No Temp Variable, Not Recommended)
This method uses addition/subtraction to swap without extra variables, but it carries overflow risks for large numbers:
a = 20 b = 10 a = a + b # a = 20 + 10 = 30 b = a - b # b = 30 - 10 = 20 a = a - b # a = 30 - 20 = 10
The end result is still a=10, b=20.
3. XOR Swap (No Temp Variable, Integer-Only)
This leverages bitwise XOR properties (same bits = 0, different bits = 1) to swap integers:
a = 20 b = 10 a = a ^ b # a = 20 ^ 10 = 30 (binary: 10100 ^ 01010 = 11110) b = a ^ b # b = 30 ^ 10 = 20 a = a ^ b # a = 30 ^ 20 = 10
Again, you end up with a=10, b=20.
If your output is 20 (either a stays 20, or b becomes 20 but a doesn't change), you almost certainly have a bug in your swap code. Here are the most common scenarios:
- Incomplete Swap: You only ran one assignment instead of the full sequence. For example:
Now botha = 20 b = 10 b = a # b becomes 20, but a remains 20aandbare 20—so you'll see 20 in your results. - Missing Final Step: If you used the arithmetic swap but skipped the last line, like:
Here,a = 20 + 10 = 30 b = 30 - 10 = 20 # Forgot to run a = a - bbis 20 andais 30—so if you're checkingb, you'll see 20. - Accidental No-Op: If you wrote something like
a = a(a no-operation),awill stay 20 forever.
If you can share the exact code you're running, I can give you a more precise breakdown—but these are the most likely culprits based on your question.
内容的提问来源于stack exchange,提问作者Kumar Gaurav

