最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
c/c++ 数据结构和算法-变量交换例子
时间:2022-06-25 08:04:25 编辑:袖梨 来源:一聚教程网
一:c语言版本
#include
void swap(int x,int y);
void swap_p(int *px,int *py);
#define swap_m(x,y,t) ((t)=(x),(x)=(y),(y)=(t))
int main(void)
{
int a,b,temp;
a=1;
b=10;
printf("a=%d,b=%dn",a,b);
//swap_p(&a,&b);
swap_m(a,b,temp);
printf("a=%d,b=%dn",a,b);
return 0;
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
void swap_p(int *px,int *py)
{
int temp;
temp=*px;
*px=*py;
*py=temp;
}
gcc编译后 执行./a.out
[web@ztx dev_local]$ ./a.out
a=1,b=10
a=10,b=1
[web@ztx dev_local]$
二:c++版本
demo1.
#include
using namespace std;
int main()
{
int a, b, tmp;
a = 1;
b = 10;
cout << "a = " << a << ", b = " << b << endl;
tmp = a;
a = b;
b = tmp;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
demo2.
#include
using namespace std;
void swap(int *px, int *py);
int main()
{
int a,b;
a = 1;
b = 10;
cout << "传指针的方法: " << endl;
cout << "a = " << a << ", b = " << b << endl;
// 拷贝的指针(地址)
swap(&a,&b);
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
void swap(int *px, int *py)
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}