您的位置:首页 > 其它

交换两个数的三种方法

2015-04-08 19:18 363 查看
// 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;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: