您的位置:首页 > 编程语言 > C语言/C++

C语言学习笔记:07_交换两个数的多个方法

2015-07-05 13:53 651 查看
/*
* 07_交换两个数的多个方法.c
*
*  Created on: 2015年7月4日
*      Author: zhong
*/

//交换两类的几种算法

#include <stdio.h>
#include <stdlib.h>

//1:使用第三方变量
void use_temp(){
int a=10,b=11;
int temp=a;
a=b;
b=temp;
printf("使用第三方变量:a=%d,b=%d\n",a,b);
}

//2:使用指针交换两个数
void user_swap(int *a, int *b) {
int c;
c = *a;
*a = *b;
*b = c;
printf("使用指针:a=%d,b=%d\n",a,b);
}

//3:使用+ -法一  :这种方法当a,b过大,相加时可能会溢出
void use_math_add_sub_01(){
int a=10,b=11;
a=a+b;
b=a-b;
a=a-b;
printf("使用加减法一:a=%d,b=%d\n",a,b);
}

//4:使用+ -法二
void use_math_add_sub_02(){
int a=10,b=11;
a=b-a; //1
b=b-a; //11-1=10
a=a+b; // 1+10=11
printf("使用加减法二:a=%d,b=%d\n",a,b);
}

//4:使用^(异或)算法
void use_or(){
int a=10,b=11;
a=a^b; //1
b=a^b; //11-1=10
a=a^b; // 1+10=11
printf("使用^(异或)算法:a=%d,b=%d\n",a,b);
}

int main7() {
use_temp();
use_math_add_sub_01();
use_math_add_sub_02();
use_or();

//	system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: