博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C语言----结构体---结构体与函数
阅读量:4310 次
发布时间:2019-06-06

本文共 1565 字,大约阅读时间需要 5 分钟。

 

结构作为参数的函数

  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

你可能感兴趣的文章
Laravel框架学习笔记之任务调度(定时任务)
查看>>
laravel 定时任务秒级执行
查看>>
浅析 Laravel 官方文档推荐的 Nginx 配置
查看>>
Swagger在Laravel项目中的使用
查看>>
Laravel 的生命周期
查看>>
CentOS Docker 安装
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
Mysql出现Table 'performance_schema.session_status' doesn't exist
查看>>
MySQL innert join、left join、right join等理解
查看>>
vivado模块封装ip/edf
查看>>
sdc时序约束
查看>>
Xilinx Jtag Access/svf文件/BSCANE2
查看>>
NoC片上网络
查看>>
开源SoC整理
查看>>
【2020-3-21】Mac安装Homebrew慢,解决办法
查看>>
influxdb 命令行输出时间为 yyyy-MM-dd HH:mm:ss(年月日时分秒)的方法
查看>>
已知子网掩码,确定ip地址范围
查看>>
判断时间或者数字是否连续
查看>>