C++ Primer 笔记二

本文详细介绍了在C++中通过引用、指针、异或操作和加减法四种方法实现变量交换的过程,提供了不同的编程思路和优化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * main.cpp
 *  Created on: 2012-2-16
 *      Author: XXX
 */

#include <iostream>
using namespace std;
void swap(int& first, int& secn);
void swap2(int& first, int& secn);
void swap3(int *first, int* secn);
void swap4(int &first, int &secn);
int main() {
//>>>>>>>>>>>>>>>>>>>>>>>6
	int firstn, secn;
	cout << "please input two num " << endl;
	cin >> firstn >> secn;
	swap4(firstn, secn);
	cout << firstn << endl;
	cout << secn << endl;
	for (int i = firstn, j = 0; i <= secn; i++, j++) {
		if (j % 10 == 0)
			cout << endl;
		cout << i << "	";
	}

	return 0;
}

/**
 * 加减法交换数
 */
void swap(int& first, int& secn) {
	if (first > secn) {
		first += secn;
		secn = first - secn;
		first = first - secn;
	}
}
/**
 * 异或法交换数
 * 原理:一个数同另一数连续异或2次,可还原为自已
 */
void swap2(int& first, int& secn) {
	if (first > secn) {
		first = first ^ secn;
		secn = first ^ secn;
		first = first ^ secn;
	}
}
/**
 * 指针交换法
 */
void swap3(int *first, int* secn) {
	if (*first > *secn) {
		int tem = *first;
		*first = *secn;
		*secn = tem;
	}
}
/**
 *引用交换法
 */
void swap4(int &first, int &secn) {
	if (first > secn) {
		int tem = first;
		first = secn;
		secn = tem;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值