问题简述:
用结构体算出某一天的下一天是什么时候
问题思路:
用两个数组分别存储闰年与非闰年的每月天数
并用函数判断是否是闰年,返回的0和1刚好就是数组的行号
输入的月刚好就是列地址的列号
极其精彩
#include <stdio.h>
struct date_rec
{
int day;
int month;
int year;
} ;
struct date_rec current_date;
int days_of_month[][13] = {{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
} ;//用数组代替了闰年的判断
int is_leap(int year)
{
return ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)));
}
void input_date(struct date_rec *current_date)
{
printf("请输入当前日期(年 月 日):");
scanf("%d%d%d", ¤t_date->year, ¤t_date->month, ¤t_date->day);
}
void increment_date(struct date_rec *current_date)
{
current_date->day++;
if (current_date->day > days_of_month[is_leap(current_date->year)][current_date->month])
{
current_date->day = current_date->day - days_of_month[is_leap(current_date->year)][current_date->month]
;
current_date->month++;
if (current_date->month > 12)
{
current_date->year++;
current_date->month = current_date->month - 12;
}
}
}
void output_date(struct date_rec *current_date)
{
printf("当前日期:%d年%d月%d日!", current_date->year,
current_date->month, current_date->day);
}
int main()
{
input_date(¤t_date);
increment_date(¤t_date);
output_date(¤t_date);
return 0;
}
自己的做法:
缺点:用了太多的if else语句,结构混乱
程序复杂
学到:(*current_date).day==current->day
#include <stdio.h>
#include <stdlib.h>
struct date_rec
{
int day ;
int month ;
int year ;
} ;
void input_date(struct date_rec *current_date);
void increment_date(struct date_rec *current_date);
void output_date(struct date_rec *current_date);
int main()
{
struct date_rec current_date ;
void input_date();
void increment_date();
void output_date();
input_date(¤t_date);
increment_date(¤t_date);
output_date(¤t_date);
}
void input_date(struct date_rec *current_date)
{
printf("请输入当前日期(年 月 日):");
scanf("%d%d%d",¤t_date->year,¤t_date->month,¤t_date->day);
}
void increment_date(struct date_rec *current_date)
{
/* int d,m,y;
d=*(current_date).day;
m=*(current_date).month;
y=*(current_date).year;*/
if((*current_date).month==12&&(*current_date).day==31)
{
(*current_date).year+=1;
(*current_date).month=1;
(*current_date).day=1;
}
else
{
if((*current_date).month==2&&(*current_date).day==28||(*current_date).day==29)
{
if(((*current_date).year%4==0&&(*current_date).year%100!=0)||(*current_date).year%400==0)
{
if((*current_date).day==29)
{
(*current_date).month=3;
(*current_date).day=1;
}
else
{
(*current_date).day+=1;
}
}
else if((*current_date).day==28)
{
(* current_date).month=3;
(*current_date).day=1;
}
}
else if( (*current_date).month==4|| (*current_date).month==6|| (*current_date).month==9 ||(*current_date).month==11)
{
if((*current_date).day==31)
{
(*current_date).month+=1;
(*current_date).day=1;
}
}
else if((*current_date).day==30)
{
(*current_date).month+=1;
(*current_date).day=1;
}
else
{
(*current_date).day+=1;
}
}
}
void output_date(struct date_rec *current_date)
{
printf("当前日期:%d年%d月%d日!" ,current_date->year,current_date->month,current_date->day);
}