[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
<>题目:使用函数实现两个数的代码
<>常规思路:
定义函数,调用函数,完成交换。
你的代码是否和下面一样呢?
#include<stdio.h> #include<stdlib.h> void Swap(int a,int b) { int tmp = a; a =
b; b = tmp; } int main() { int x = 10; int y = 20; Swap(x,y); printf("%d %d\n",
x, y); system("pause"); return 0; }
如果你的代码和上面一样,那恭喜你,成功的掉入到坑。
为什么呢?这个时候我们就要打破常规的思路,因为涉及到了实参和形参。
<>注意:
定义函数里的参数叫做形参(形式参数)调用函数里的参数叫做实参(实际参数)
函数的形参是实参的一份拷贝(副本),上面的代码中,只是交换定义函数里的参数,只对副本(形参)进行交换当然不会实现对实参(我们实际要交换的变量)的交换。也就是说:我们只是交换a和b的值,并没有对x和y进行交换,我们真正要交换的是a和b的值。
这个时候就要使用传指针的方法来修改函数外部的变量。对形参进行指针类型的转变,相当于把两个毫无关系的参数连接起来,以下是具体代码(仅供参考)
#include<stdio.h> #include<stdlib.h> void Swap(int* a,int* b) { int tmp = *a; *
a= *b; *b = tmp; } int main() { int x = 10; int y = 20; //注意,这里传的参数是地址 Swap(&x,&
y); printf("%d %d\n", x, y); system("pause"); return 0; }
上面是传地址,也可以通过传引用的方式进程参数的传递
<>心得体会:
第一次理解起来稍微有点困难,这个应该算函数里较难的一种,不过第二次再去看的话,理解起来就容易多了,在错误中不断成长,不断努力,加油!