问题描述
#include<stdio.h>
int main()
{
int a=20,b=30;
a=a+b;
b=a-b;
a=a-b;
return 0;
}
我可以用这个程序来交换正负值吗.
Can I use this program to swap both positive and negative values.
推荐答案
在没有临时持有者的情况下交换变量的算法使用按位异或运算,而不是减法.因此,使用名为 a
和 b
的变量,我们将:
The algorithm for swapping variables without a temporary holder uses the bitwise XOR operation, not subtraction. So, using variables named a
and b
, we'd have:
a=a^b;
b=a^b;
a=a^b;
您的代码确实适用于我使用a
和b
的一些整数值对其进行测试的少数情况,但XOR是传统的做法.正如评论者@wildplasser 指出的那样,XOR 是约定的原因是整数加法和减法可能会溢出,给出错误的结果,而 XOR 则不能.
Your code does work for the few cases I tested it with using some integral values for a
and b
, but XOR is the conventional way of doing it. As commenter @wildplasser pointed out, the reason XOR is the convention is that integer addition and subtraction can overflow, giving incorrect results, whereas XOR cannot.
这篇关于这种方式是否更适合在 c 中交换两个没有 temp 的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!