C语言----结构体---结构体与函数

 

结构作为参数的函数

  1. 整个结构可以作为参数传入函数
  2. 这时是在函数中新建了一个结构变量,并复制调用这个结构的值(重点,只是把值传入函数,而函数外面真正的变量并没有改变,与数组不同)
  3.  函数也可以返回一个结构

直接来个简单的例子吧:

问题:用户输入今天的日期,输出明天的日期。

提示:闰年,每个月最后一天,

 

代码:

#include <stdio.h>
#include <stdbool.h>
/* 根据今天的日期算出明天的日期。*/

 

//结构体放在函数外侧,相当于一个全局变量,所有的函数都能使用。
struct date
{
  int month;
  int day;
  int year;
};    //记住这个分号

 

bool is_leap(struct date d);  //判断是否为闰年
int numbersofdays(struct date d);  //给出这个月的天数

 

 

int main(int argc, char const *argv[])
{
  struct date today;   //定义两个结构体变量
  struct date tomorrow;
  int days;
  int flag=1;  //实现输入控制

  printf("请输入今天的日期(9-24-2012):");
  scanf("%i-%i-%i",&today.month,&today.day,&today.year);

  days = numbersofdays(today);
  tomorrow = today;  //可以像一般变量一样赋值
  if(today.day<days && today.month <=12){
    tomorrow.day = today.day + 1;
  }else if(today.day == days && today.month <12){
    tomorrow.day = 1;
    tomorrow.month +=1;
  }else if(today.day == days && today.month == 12){
    tomorrow.day =1;
    tomorrow.month =1;
    tomorrow.year+=1;
  }else{
    flag = 0;
    printf("输入有误!");
  }

  if(flag){
    printf("明天的日期是:");
    printf("%i-%i-%i\n",tomorrow.month,tomorrow.day,tomorrow.year);
  }

  return 0;
}

bool is_leap(struct date d)
{
  bool is = false;
  if((d.year%4==0 && d.year%100!=0) || d.year%400==0)
    is = true;
  return is;
}


int numbersofdays(struct date d)
{
  int days;
  int dayspermonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
  if(d.month==2 && is_leap(d))
  {
    days = 29;
  }
  else

  {
    days = dayspermonth[d.month-1];
  }

  return days;
}

 

 

转载于:https://www.cnblogs.com/fakke/p/7502959.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值