C语言 交换两个数字
2018-02-08 本文已影响51人
863cda997e42
//交换两个数值的c语言代码:
//关键是注意程序的效率问题,还有引用和传值的区别:
#include <stdio.h>
void swap(int *a,int *b); //void swap(int &a, int &b);第二种方法;
int main()
{
int number1,number2;
printf("please input two number you want to exchange:\n");
scanf("%d%d",&number1,&number2);
printf("before exchange the number is %d %d.\n",number1, number2);
swap(& number1,& number2); //swap(number1,number2);
printf("after exchange the number is %d %d.\n",number1,number2);
return 0;
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a =*b;
*b=temp;
}
/*也可以应用引用来解决这类问题,效率更高;
* void swap(int &a,int &b) //引用就是给变量起一个别名,在程序运行的过程中没有产生副本,减少了系统的开销也达到
* 交换数据的真正目的;
* {
* int temp;
* temp=a;
* a = b;
* b= temp;
* }
*
*/
通过 ^ 运算符可以不借助中间变量交换两个数字。
x = x^y;
y = y^x;
x = x^y;