You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于两变量交换代码的原理及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.

Common Variable Swap Logic

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.

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.

Why Are You Seeing 20 as a Result?

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:
    a = 20
    b = 10
    b = a  # b becomes 20, but a remains 20
    
    Now both a and b are 20—so you'll see 20 in your results.
  • Missing Final Step: If you used the arithmetic swap but skipped the last line, like:
    a = 20 + 10 = 30
    b = 30 - 10 = 20
    # Forgot to run a = a - b
    
    Here, b is 20 and a is 30—so if you're checking b, you'll see 20.
  • Accidental No-Op: If you wrote something like a = a (a no-operation), a will 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:51:38