使用指针和不使用指针来交换a与b的值

一、代码

 1 #include <iostream>
 2 using namespace std;
 3 void swap1(int x,int y)
 4 {
 5     int t=x;
 6     x=y;
 7     y=t;
 8     cout<<"a与b交换后的值为:x="<<x<<" y="<<y<<endl;
 9 }
10 void swap2(int *x,int *y)
11 {
12     int temp;
13     temp=*x;
14     *x=*y;
15     *y=temp;
16     cout<<"a与b交换后的值为:x="<<*x<<" y="<<*y<<endl;
17 }
18 void main()
19 {
20     cout<<"请输入a和b的值:"<<endl;
21     int a,b;
22     cin>>a>>b;
23     cout<<"a和b交换前的值为:a="<<a<<" b="<<b<<endl;
24     swap1(a,b);
25     swap2(&a,&b);
26     cout<<"a和b交换后的值为:a="<<a<<" b="<<b<<endl;
27 }

二、运行

原文地址:https://www.cnblogs.com/f59130/p/3338810.html