交换两个数是在编程中经常会用到的,当然我们可以用很常见的方式来实现,也可以各种稀奇古怪的方法来做。这里我们用三种比较常规的方式来做,太过古怪的方法个人觉得没有太大必要。实例代码上传至:https://github.com/chenyufeng1991/swapfunction
(1)使用指针
实现如下:
//
// main.c
// SwapFunc
//
// Created by chenyufeng on 16/2/3.
// Copyright © 2016年 chenyufengweb. All rights reserved.
//
#include <stdio.h>
void swap01(int *a,int *b);
int main(int argc, const char * argv[]) {
int a = 1;
int b = 2;
printf("交换前:a = %d,b = %d\n",a,b);
swap01(&a, &b);
printf("交换后:a = %d,b = %d\n",a,b);
return 0;
}
//最常规的交换;
void swap01(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
</stdio.h>
//
// main.c
// SwapFunc
//
// Created by chenyufeng on 16/2/3.
// Copyright © 2016年 chenyufengweb. All rights reserved.
//
#include <stdio.h>
void swap02(int *a,int *b);
int main(int argc, const char * argv[]) {
int a = 1;
int b = 2;
printf("交换前:a = %d,b = %d\n",a,b);
swap02(&a, &b);
printf("交换后:a = %d,b = %d\n",a,b);
return 0;
}
//不用第三个数;
void swap02(int *a,int *b){
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
</stdio.h>(3)异或
//
// main.c
// SwapFunc
//
// Created by chenyufeng on 16/2/3.
// Copyright © 2016年 chenyufengweb. All rights reserved.
//
#include <stdio.h>
/**
* 由于我这里用的是C语言,所以不能使用引用。C++中可以使用引用。
引用的函数定义:
void swap04(int &a,int &b){
...
}
*/
void swap03(int *a,int *b);
int main(int argc, const char * argv[]) {
int a = 1;
int b = 2;
printf("交换前:a = %d,b = %d\n",a,b);
swap03(&a, &b);
printf("交换后:a = %d,b = %d\n",a,b);
return 0;
}
//异或,使用二进制位进行计算;
void swap03(int *a,int *b){
*a = *a ^ *b;
*b = *b ^ *a;
*a = *a ^ *b;
}
</stdio.h>
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号