版权声明:本文由 Micheal 博客 创作,转载请附带链接,有问题欢迎交流。 https://blog.csdn.net/qq_42887760/article/details/83930403
swap()函数
方法一:指针法
实参:&a
形参:*x
#include<stdio.h>
void MySwap(int *x,int *y);
int main(){
int a=5,b=9;
printf("交换前:a=%d,b=%d \n",a,b);
MySwap(&a,&b);
printf("交换后:a=%d,b=%d \n",a,b);
return 0;
}
void MySwap(int *x,int *y){
int temp=*x;//如果写成int *p=x;x=y;y=p;则还是无法改变实参的值
*x=*y;
*y=temp;
}
方法二:引用法
实参:a
形参:&x
#include<stdio.h>
void MySwap(int &x,int &y);
int main(){
int a=5,b=9;
printf("交换前:a=%d,b=%d \n",a,b);
MySwap(a,b);
printf("交换后:a=%d,b=%d \n",a,b);
return 0;
}
void MySwap(int &x,int &y){
int temp=x;
x=y;
y=temp;
}
对于函数体的编写方式:
//方法一: 基本方法
/*
int temp = 0;
temp = b;
b = a ;
a = temp;
*/
//方法二: 数学方法
/*
a = a + b;
b = a - b;
a = a - b;
*/
参考博客:
1.https://blog.csdn.net/duan_jin_hui/article/details/50879338
2.https://blog.csdn.net/hyqsong/article/details/51371381
3.https://blog.csdn.net/Scalpelct/article/details/52226415
4.https://blog.csdn.net/litao31415/article/details/40183647