交换两个数的三种方法

// demo4.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

void swap1(int &a,int &b)  //使用引用
{
    int temp;
    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^=b;
    b^=a;
    a^=b;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int e=100;
    int f=1000;
    swap1(e,f);
    cout<<e<<"\t"<<f<<endl;
    e++;
    f++;
    swap2(e,f);
    cout<<e<<"\t"<<f<<endl;
    e++;
    f++;
    swap3(e,f);
    cout<<e<<"\t"<<f<<endl;
    return 0;
}

 

异或操作不是将两个数相加,所以不用担心会出现越界的问题

image

posted @ 2015-04-08 19:18  WQZ321123  阅读(203)  评论(0)    收藏  举报