函数(4)中教学了函数的嵌套使用与函数的链式访问,以及界说函数时参数与返回范例的一些题目。
一、函数的嵌套
函数的嵌套指的是一个函数调用了另一个函数。
//函数的嵌套调用练习
//操持一个函数:输入年份和月份得到相应的天数
//比方:
//输入:2025 3
//输出:31- #include <stdio.h>
- //日期转换函数
- int Get_Days_From_Year_And_Month(int fun_year, int fun_month)
- {
- int arr_days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
- int day = arr_days[fun_month-1];//C语言下标从0开始,减去1之后,输入月份恰好对应数组中的内容 1-1=0------>对应31
- if (is_leap_year(fun_year) && (fun_month == 2))
- {
- ++day;//如果是闰年,二月份为29天
- }
- return day;
- }
- //闰年的判断
- int is_leap_year(int fun1_year)
- {
- if ((fun1_year % 4 == 0 && fun1_year % 100 != 0) || fun1_year % 400 == 0)
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
- int main()
- {
- int year = 0;
- int month = 0;
- int days = 0;
- scanf("%d%d",&year,&month);
- days=Get_Days_From_Year_And_Month(year,month);
- printf("%d year %d month has %d days.",year,month,days);
- return 0;
- }
复制代码 运行结果:
二、函数的链式访问
函数的链式访问指的是一个函数的返回结果作为另一个函数的参数。- #include <stdio.h>
- #include <string.h>
- int main()
- {
- int re = strlen("abcdefgh");
- printf("re=%d\n",re);
- //函数的链式访问
- printf("计算结果:%d\n", strlen("abcdefgh"));
- }
复制代码 运行结果:
练习参考: - #include <stdio.h>
- int main()
- {
- printf("%d", printf("%d", printf("%d",123)));
- }
复制代码 运行结果:
三、函数参数与返回范例的留意事项
(1)函数的返回范例不写时,默认返回范例为int,为此当不须要返回时可以写void
参考代码:- #include <stdio.h>
- //函数的返回类型不写时,默认返回类型为int
- //为此当不需要返回时可以写void
- test(void)
- {
- printf("hello\n");
- }
- int main()
- {
- int ret = test();
- printf("ret=%d\n", ret);
- return 0;
- }
复制代码 运行结果:
(2)函数界说时若没有情势参数,则实参传入形参时没有影响,但是这个是非常不公道的。
参考代码:- #include <stdio.h>
- void test()
- {
- printf("hello\n");
- }
- int main()
- {
- test();
- test(1);
- test(23);
- test(235);
- return 0;
- }
复制代码 运行结果:
为了办理这种不公道性,不须要传入参数时我们在函数的界说时在参数中参加void即可。
修改结果:- #include <stdio.h>
- void test(void)
- {
- printf("hello\n");
- }
- int main()
- {
- test();
- return 0;
- }
复制代码 运行结果:
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|