C语言(21)---------------------->函数(4)

[复制链接]
发表于 2025-10-21 00:31:18 | 显示全部楼层 |阅读模式
函数(4)中教学了函数的嵌套使用与函数的链式访问,以及界说函数时参数与返回范例的一些题目。
一、函数的嵌套

函数的嵌套指的是一个函数调用了另一个函数。
//函数的嵌套调用练习
//操持一个函数:输入年份和月份得到相应的天数
//比方:
//输入:2025 3
//输出:31
  1. #include <stdio.h>
  2. //日期转换函数
  3. int Get_Days_From_Year_And_Month(int fun_year, int fun_month)
  4. {
  5.         int arr_days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
  6.         int day = arr_days[fun_month-1];//C语言下标从0开始,减去1之后,输入月份恰好对应数组中的内容 1-1=0------>对应31
  7.         if (is_leap_year(fun_year) && (fun_month == 2))
  8.         {
  9.                 ++day;//如果是闰年,二月份为29天
  10.         }
  11.         return day;
  12. }
  13. //闰年的判断
  14. int is_leap_year(int fun1_year)
  15. {
  16.         if ((fun1_year % 4 == 0 && fun1_year % 100 != 0) || fun1_year % 400 == 0)
  17.         {
  18.                 return 1;
  19.         }
  20.         else
  21.         {
  22.                 return 0;
  23.         }
  24. }
  25. int main()
  26. {
  27.         int year = 0;
  28.         int month = 0;
  29.         int days = 0;
  30.         scanf("%d%d",&year,&month);
  31.         days=Get_Days_From_Year_And_Month(year,month);
  32.         printf("%d year %d month has %d days.",year,month,days);
  33.         return 0;
  34. }
复制代码
运行结果:
 
二、函数的链式访问

 函数的链式访问指的是一个函数的返回结果作为另一个函数的参数。
  1. #include <stdio.h>
  2. #include <string.h>
  3. int main()
  4. {
  5.         int re = strlen("abcdefgh");
  6.         printf("re=%d\n",re);
  7.         //函数的链式访问
  8.         printf("计算结果:%d\n", strlen("abcdefgh"));
  9. }
复制代码
运行结果:

练习参考: 
  1. #include <stdio.h>
  2. int main()
  3. {
  4.         printf("%d", printf("%d", printf("%d",123)));
  5. }
复制代码
运行结果:

三、函数参数与返回范例的留意事项

 (1)函数的返回范例不写时,默认返回范例为int,为此当不须要返回时可以写void
参考代码:
  1. #include <stdio.h>
  2. //函数的返回类型不写时,默认返回类型为int
  3. //为此当不需要返回时可以写void
  4. test(void)
  5. {
  6.         printf("hello\n");
  7. }
  8. int main()
  9. {
  10.         int ret = test();
  11.         printf("ret=%d\n", ret);
  12.         return 0;
  13. }
复制代码
运行结果:

(2)函数界说时若没有情势参数,则实参传入形参时没有影响,但是这个是非常不公道的。
参考代码:
  1. #include <stdio.h>
  2. void test()
  3. {
  4.     printf("hello\n");
  5. }
  6. int main()
  7. {
  8.     test();
  9.     test(1);
  10.     test(23);
  11.     test(235);
  12.     return 0;
  13. }
复制代码
运行结果:

 为了办理这种不公道性,不须要传入参数时我们在函数的界说时在参数中参加void即可。
修改结果:
  1. #include <stdio.h>
  2. void test(void)
  3. {
  4.         printf("hello\n");
  5. }
  6. int main()
  7. {
  8.         test();
  9.         return 0;
  10. }
复制代码
运行结果:


 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表