22-语言入门-22-日期计算

来源:互联网 发布:小学奥数教材知乎 编辑:程序博客网 时间:2024/06/05 16:59

题目地址: http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=75

描述
如题,输入一个日期,格式如:2010 10 24 ,判断这一天是这一年中的第几天。
输入
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每行的输入数据都是一个按题目要求格式输入的日期。
输出
每组输入数据的输出占一行,输出判断出的天数n
样例输入
3
2000 4 5
2001 5 4
2010 10 24
样例输出
96
124

297

代码:

#include <stdio.h>
//计算一年中的哪一天
static int calDay(int year,int month,int day);
//返回月份的天数
static int getAllDay(int year,int month);
int main()
{
     int readLen = 0;
     scanf("%d",&readLen);
     getchar();
     while(readLen > 0)
     {
          int year = 0;
          int month = 0;
          int day = 0;
          scanf("%d %d %d",&year,&month,&day);
          getchar();
          printf("%d\n",calDay(year,month,day));
          --readLen;
     }
     return 0;
}
//计算一年中的哪一天
static int calDay(int year,int month,int day)
{
     int result = 0;
     int index = 1;
     for(;index < month;++index)
     {
          result += getAllDay(year,index);
     }
     return result + day;
}
//返回月份的天数
static int getAllDay(int year,int month)
{
     switch(month)
     {
          case 0:
               return 0;
          case 1:
          case 3:
          case 5:
          case 7:
          case 8:
          case 10:
          case 12:
               return 31;
          case 4:
          case 6:
          case 9:
          case 11:
               return 30;
          case 2:
               {
                    if(year % 4 == 0)
                    {
                         return 29;
                    }
                    else
                    {
                         return 28;
                    }
               }
     }
}
该题需要明白闰月的判断,需要知道除了2月份,其他月份的天数。

另外C和C++的switch中只能针对 int char 类型的case,而不能对字符串进行case,

而且break结束标记不像Java C#要求的那么严格,

如此较为便利,但是也可能带来错误隐患,使用时要严格检查

0 0
原创粉丝点击