C++中几种不同交换两个数的方法
#include<iostream>
using namespace std;
void swapr(int & a, int &b);
void swapp( int * a, int * b);
void swapv(int a,int b);
int main()
{
int a,b;
cout<<"请输入a"<<endl;
cin>>a;
cout<<"请输入b"<<endl;
cin>>b;
cout<<"交换前"<<endl;
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"使用引用交换"<<endl;
swapr(a,b);
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"使用指针交换"<<endl;
swapp(&a,&b);
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"使用值交换"<<endl;
swapv(a,b);
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
return 0;
}
void swapr(int & a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void swapp( int * a, int * b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void swapv(int a,int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
我们可以发现使用值传递并不能交换两个数
using namespace std;
void swapr(int & a, int &b);
void swapp( int * a, int * b);
void swapv(int a,int b);
int main()
{
int a,b;
cout<<"请输入a"<<endl;
cin>>a;
cout<<"请输入b"<<endl;
cin>>b;
cout<<"交换前"<<endl;
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"使用引用交换"<<endl;
swapr(a,b);
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"使用指针交换"<<endl;
swapp(&a,&b);
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"使用值交换"<<endl;
swapv(a,b);
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
return 0;
}
void swapr(int & a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void swapp( int * a, int * b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void swapv(int a,int b)
{
int temp;
temp = a;
a = b;
b = temp;
}