能够实现两数在函数中成功交换的两种方法

/* 实现两个数在函数成功交换的两种方法 */
#include <cstdlib>
#include <iostream>

using namespace std;


int swap(int &p,int &q){
	int temp;
	temp=p;
	cout << "------------------swap方法体内" << endl;
	cout <<"swap方法使用的是地址对应的值交换" << endl; 
	cout << ".........形式参数p和q其实分别代表传入的a,b值的地址.....a的地址....."<< &p << "....b的地址........" << &q<<endl; 
	cout <<"a的值:"<< p  << ",b的值:" << q << endl; 
	p=q;
	q=temp;
	cout << "swap方法体内---------------------" <<endl; 
	return 0;
}

int swap1(int *p,int *q)
{
	cout <<"----------------swap1方法体内" << endl; 
	cout <<"swap1方法使用的是地址对应的值交换" << endl; 
	int temp;
	cout << "a的地址" << p << ",b的地址为" << q << endl;
	cout << "a的值" << *p << ",b的值为" << *q << endl; 
	temp=*p;
	*p=*q;
	*q=temp;
	cout << "swap1方法体内---------------------" << endl;
	return 0;
	}

int main(int argc, char *argv[])
{
	int a,b;
	int *p=&a;
	int *q=&b;
	
	cin >> a >> b;
	cout <<"*****a的地址&a:"<< &a << "*********p为地址:" << p <<endl;
	swap (a,b);
	cout <<"swap方法:"<<"交换后a的值:" << a << ",交换后b的值" << b << endl;
	swap1(p,q); 
	cout <<"swap1方法:"<<"交换后a的值:" << a << ",交换后b的值" << b << endl;
	swap1(&a,&b);
	cout <<"swap1方法:"<<"交换后a的值:" << a << ",交换后b的值" << b << endl;

    
	system("PAUSE");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值