结构作为函数参数:

  声明了一个结构就有了一种自定义的数据类型,这个数据类型和int、float、double一样,int等基本类型可以作为函数的参数,那么这种个自定义的结构类型也应该可以作为函数参数,比如:

int numberofDays(struct date d);函数numberofDays的参数就是一种结构变量。

  整个结构是可以作为参数的值传入函数的,这时是在函数内新建一个结构变量,并复制调用者的结构的值,这和数组是完全不一样的。结构除了可以作为参数,也可以作为返回值,例如下述程序中,直接将结构变量d传给另外两个函数:

 1 #include <stdio.h>
 2 #include <stdbool.h>
 3 
 4 struct date{
 5     int month;
 6     int day;
 7     int year;
 8 };
 9 
10 bool isLeap(struct date d); //判断是否闰年 ,若是返回true,否则返回false 
11 int numberofDays(struct date d);
12 
13 int main(int argc,char const *argv[]){
14 
15     struct date today,tomorrow;    //定义两个结构变量 
16     printf("Enter today's date (mm dd yyyy):");      //输入今天的日期 
17     scanf("%i %i %i",&today.month,&today.day,&today.year);//.运算符比&运算符优先级高 
18     
19     if(today.day != numberofDays(today)){  //如果today不是这个月的最后一天,那么明天就是今天加1,年和月不变 
20         tomorrow.day=today.day +1;
21         tomorrow.month=today.month;
22         tomorrow.year=today.year;
23     }else if(today.month == 12){  //如果today是这个月的最后一天,且月份是12月份,那么第二天就是新的一年,月日都是1,年加1 
24         tomorrow.day=1;
25         tomorrow.month=1;
26         tomorrow.year=today.year+1;
27     }else{                 //如果today不是这个月的最后一天,且月也不是12月,那么明天就是下个月,月加1,day是1,year不变。 
28         tomorrow.day=1;
29         tomorrow.month=tomorrow.month+1;
30         tomorrow.year=today.year;
31     }
32     
33     printf("Tomorrow's date is %i-%i-%i.\n'",tomorrow.year,tomorrow.month,tomorrow.day);
34     
35     return 0;
36 }
37 
38 int numberofDays(struct date d){
39     int days;
40     const int daysPerMonth[12]={31,28,31,30,31,30,31,31,30,31,30,31};//每个月有多少天 
41     if(d.month==2&&isLeap(d)) //如果是2月且是闰年,days是29天 
42         days=29;
43     else
44         days=daysPerMonth[d.month-1];//否则直接输出该月的天数,之所以减1是因为数组是从0开始下标的 
45     return days;   //单一出口 
46 }
47 
48 bool isLeap(struct date d){
49     bool leap=false;
50     if((d.year%4==0 && d.year%100!=0)||d.year%400==0)
51         leap =true;
52     return leap;
53 } 
View Code

相关文章: