小学教育专硕讨论区程序员C语言

小朋友学C++(14):两数交换

2017-11-15  本文已影响44人  海天一树X

之前学C语言的时候,咱们直接在main函数中使用“异或”位运算符,很容易实现了两数交换。
本节课将在此基础上,把交换两个数的算法,封装到swap函数中。这样不管是哪个地方想要交换两个数,调用swap函数就可以了。

程序1:

#include <iostream>
using namespace std;

void swap(int m, int n)
{
    cout << "Memory address of m: " << &m << endl;
    cout << "Memory address of n: " << &n << endl;
    
    cout << "\nBefore Swap:" << endl;
    cout << "m = " << m << endl;
    cout << "n = " << n << endl;
    
    m ^= n;
    n ^= m;
    m ^= n;
    
    cout << "\nAfter Swap:" << endl;
    cout << "m = " << m << endl;
    cout << "n = " << n << endl;    
}

int main(int argc, char** argv) 
{
    int a = 1;
    int b = 2;

    cout << "Memory address of a: " << &a << endl;
    cout << "Memory address of b: " << &b << endl;  
    
    swap(a, b);
    
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    
    return 0;
}

运行结果:

Memory address of a: 0x7fff90371cd8
Memory address of b: 0x7fff90371cdc
Memory address of m: 0x7fff90371c9c
Memory address of n: 0x7fff90371c98

Before Swap:
m = 1
n = 2

After Swap:
m = 2
n = 1
a = 1
b = 2

分析:
从结果可以看出,a和b调用swap之后,值并没对换过来。
其原因在于,形参m和n的作用域只是在swap函数内。在swap内,m = a = 1, n = b = 2,交换后m = 2, n = 1。但是,m和n的值并不会传回给a和b,导致a和b的值没有被对换。

解决方案,使用上节课讲过的引用。
程序2:

#include <iostream>
using namespace std;

void swap(int &m, int &n)
{
    cout << "Memory address of m: " << &m << endl;
    cout << "Memory address of n: " << &n << endl;
    
    cout << "\nBefore Swap:" << endl;
    cout << "m = " << m << endl;
    cout << "n = " << n << endl;
    
    m ^= n;
    n ^= m;
    m ^= n;
    
    cout << "\nAfter Swap:" << endl;
    cout << "m = " << m << endl;
    cout << "n = " << n << endl;    
}

int main(int argc, char** argv) 
{
    int a = 1;
    int b = 2;

    cout << "Memory address of a: " << &a << endl;
    cout << "Memory address of b: " << &b << endl;  
    
    swap(a, b);
    
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    
    return 0;
}

运行结果:

Memory address of a: 0x7fffd009de98
Memory address of b: 0x7fffd009de9c
Memory address of m: 0x7fffd009de98
Memory address of n: 0x7fffd009de9c

Before Swap:
m = 1
n = 2

After Swap:
m = 2
n = 1
a = 2
b = 1

分析:
使用引用后,达到了交换a和b的目的。这是因为形参m和n是实参a和b的引用,m和a是一回事,n和b是一回事。
交换m和n的值,就是交换a和b的值。



更多内容请关注微信公众号


wechat.jpg
上一篇下一篇

猜你喜欢

热点阅读