C语言计算日期
小龟从出生至今的每一天他都会在自己的龟壳上画一笔,而 20032003 年 55 月 11 日正好是他出生的第 10001000 天,请问他现在一共画了多少笔? 本帖最后由 傻眼貓咪 于 2022-2-12 15:09 编辑#include <stdio.h>
// 日期构造
typedef struct{
int year, month, day;
}Day;
// 闰年公式
int isLeap(int year){ return !(year%4) && year%100 || !(year%400); }
// 月份天数
int D(int year, int month){ return (month == 2) && isLeap(year) ? 29 : (month == 2) && !isLeap(year) ? 28 : (month < 8 && month%2) || (month > 7 && !(month%2)) ? 31 : 30; }
// 计算出生日期
Day birthday(Day day, unsigned days){
while(days--){
day.day--;
if(!day.day){
if(day.month-1 > 0) day.month--;
else{
day.month = 12;
day.year--;
}
day.day = D(day.year, day.month);
}
}
return day;
}
int compare(Day A, Day B){
if(A.year == B.year && A.month == B.month && A.day == B.day) return 1;
return 0;
}
// 计算出共画了多少笔
unsigned total(unsigned days, Day start, Day now){
for(;; days++){
start.day++;
if(start.day > D(start.year, start.month)){
start.day = 1;
start.month++;
if(start.month > 12){
start.month = 1;
start.year++;
}
}
if(compare(start, now)) return days;
}
return 0;
}
int main()
{
Day day = {2003, 5, 1};
Day now = {2022, 2, 12};
unsigned days = 1000;
Day b = birthday(day, days);
printf("出生日期:%4d-%02d-%02d\n", b.year, b.month, b.day);
printf("笔画:%u", total(days, day, now));
return 0;
} 学习 了
页:
[1]