王道机试指南 例题2.7 打印日期
题目:
代码:
#include <iostream> #include <cstdio> using namespace std; int IsSpecialYear(int n){ if((n%400==0)||(n%100!=0 && n%4==0)) return 1; return 0; } int main() { int year,n; int MD1[12]={31,28,31,30,31,30,31,31,30,31,30,31};//不是闰年 int MD2[12]={31,29,31,30,31,30,31,31,30,31,30,31};//是闰年 while(cin>>year>>n){ int month=0,day=0; if(IsSpecialYear(year)==0){//不是闰年 while(n>MD1[month]){ n=n-MD1[month]; month++; } day=n; month++; } else{//是闰年 while(n>MD2[month]){ n=n-MD2[month]; month++; } day=n; month++; } printf("%04d-%02d-%02d\n",year,month,day); } return 0; }
注意:
- 闰年的判断:不能被100整除且能被4整除,或能被400整除。
- printf函数的输出格式:(记得加上 #include <cstdio>)