#include <stdio.h> int main() { int m; int month[12]={31,28,31,30,31,30,31,31,30,31,30,31}; scanf("%d",&m); while (m--) { // 注意 while 处理多个 case // 64 位输出请用 printf("%lld") to int y,mo,d,n; scanf("%d %d %d %d",&y,&mo,&d,&n); if(y%4==0&&y%100!=0){ month[1]=29; } if(n+d<=month[mo-1]){ printf("%d-",y); if(mo<10){ printf("0"); } printf("%d-",mo); if(n+d<10){ printf("0"); } printf("%d\n",n+d); } else{ n=n-(month[mo-1]-d); while(1){ if(mo==12){ mo=0; y++; if(y%4==0&&y%100!=0){ month[1]=29; } else{ month[1]=28; } } if(n-month[mo]<=0){ break; } n-=month[mo]; mo++; } printf("%d-",y); if(mo+1<10){ printf("0"); } printf("%d-",mo+1); if(n<10){ printf("0"); } printf("%d\n",n); } } return 0; }
#include <stdio.h> int LeapYear(int y) { return (y % 400 == 0) || (y % 100 != 0 && y % 4 == 0); } int main() { int a[][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 n, y, m, d, x, flag, i; scanf("%d", &n); while (n) { scanf("%d%d%d%d", &y, &m, &d, &x); x += d; flag = LeapYear(y); for (i = m; x > a[flag][i]; i ++) { x -= a[flag][i]; if (i == 12) { y ++; flag = LeapYear(y); i = 0; } } printf("%4d-%02d-%02d\n", y, i, x); n --; } return 0; }先把日加到天数上 再计算比较方便
具体思路就是先将年月具体转换为第几天,然后再计算最后的日期.
但是要注意的是,加了时间之后还是今年吗,如果今年不是闰年那下一年是闰年吗?每一轮的数据使用完之后要进行清零处理,或者直接定义在循环内。
#include <stdio.h> int main() { int a = 0; scanf("%d", &a); int MonthDay[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; int year = 0; int month = 0; int day = 0; int sum = 0; while(~scanf("%d%d%d%d", &year, &month, &day, &sum)) { if((year%400 == 0)||(year%4 == 0 && year % 100 != 0)) MonthDay[2] = 29; int i = month; sum+=day; while(sum>MonthDay[i]) { sum-=MonthDay[i]; ++month; ++i; if(month > 12) { ++year; if((year%400 == 0)||(year%4 == 0 && year % 100 != 0)) MonthDay[2] = 29; else MonthDay[2] = 28; month = 1; i = 1; } } day = sum; printf("%4d-%02d-%02d\n",year,month,day); } return 0; }简单好理解
#include<stdio.h> typedef struct date { int year; int month; int day; }date; int Getmonthday(int year, int month) { int Day[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (month == 2 && (year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { return Day[month] + 1; } else return Day[month]; } date newdate(date d,int n) { d.day+=n; while(d.day>Getmonthday(d.year, d.month)) { d.day-=Getmonthday(d.year, d.month); d.month++; if(d.month>12) { d.year++; d.month=1; } } return d; } int main() { date d1; date d2; int n=0; int m=0; scanf("%d",&m); while(m--) { scanf("%d %d %d %d",&d1.year,&d1.month,&d1.day,&n); d2=newdate(d1,n); printf("%04d-%02d-%02d",d2.year,d2.month,d2.day); printf("\n"); } return 0; }