大家好,这里是国中之林!
❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看←
问题:
解答:
#include <iostream>
using namespace std;void swap1(int& a, int& b)
{int temp = a;a = b;b = temp;
}void swap2(int& a, int& b)
{a = a + b;b = a - b;a = a - b;
}void swap3(int& a, int& b)
{a = a ^ b;b = a ^ b;a = a ^ b;
}int main()
{int a1 = 1, b1 = 2;int a2 = 3, b2 = 4;int a3 = 5, b3 = 6;int a = 2147483647, b = 1;swap1(a1, b1);swap2(a2, b2);swap3(a3, b3);printf("after swap. . .\n");printf("a1 = %d,b1 = %d\n", a1, b1);printf("a2 = %d,b2 = %d\n", a2,b2); printf("a3 = %d,b3 = %d\n", a3, b3); swap2(a,b);printf("a = %d,b = %d\n", a, b);return 0;
}
运行结果:
注意:
- 方法二可能会溢出,所以方式三是最佳解.
记下来吧…