博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[日期类问题] 例 2.4 Day of week(九度教程第 7 题)
阅读量:3731 次
发布时间:2019-05-22

本文共 2855 字,大约阅读时间需要 9 分钟。

题目

时间限制:1 秒 内存限制:32 兆 特殊判题:否

题目描述:

We now use the Gregorian style of dating in Russia. The leap years are years with number divisible by 4 but not divisible by 100, or divisible by 400.
For example, years 2004, 2180 and 2400 are leap. Years 2004, 2181 and 2300 are not
leap.
Your task is to write a program which will compute the day of week corresponding to a given date in the nearest past or in the future using today’s agreement about dating.
输入:
There is one single line contains the day number d, month name M and year
number y(1000≤y≤3000). The month name is the corresponding English name
starting from the capital letter.
输出:
Output a single line with the English name of the day of week corresponding to
the date, starting from the capital letter. All other letters must be in lower case.
样例输入:
9 October 2001
14 October 2001
样例输出:
Tuesday
Sunday
来源:
2008 年上海交通大学计算机研究生机试真题

分析

在上题的基础上,只需要改进如下:

1. 知道今天是星期几
2. 计算日期与今天的差值
3. 求出日期是星期几

代码

#include
#include
#define ISLEAPYEAR(x) x % 100 != 0 && x % 4 == 0 || x % 400 == 0 ? 1 : 0 //简洁写法 using namespace std;int daysOfMonth[13][2] = { 0, 0, 31, 31, 28,29, 31,31, 30,30, 31,31, 30,30, 31,31, 31,31, 30,30, 31,31, 30,30, 31,31};char monthName[13][20] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; //月名 每个月名对应下标1到12char weekName[8][20] = { "", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday",}; //周名 每个周名对应下标1到7class Date //注意不要加括号 { public: int year; int month; int day; Date() //初始化日期为0/1/1 作为基准 { year = 0; month = 1; day = 1; } void update() //将日期加一天 { day++; if(day > daysOfMonth[month][ISLEAPYEAR(year)]) { day = 1; month ++; if(month > 12) { month = 1; year ++; } } }};int Abs(int x){ return (x >= 0 ? x : -1*x); }int buf[6001][13][32]; //用来存储每个日期与基准日期的差值 int main(){ Date temp; int count = 0; while(temp.year < 6000) { buf[temp.year][temp.month][temp.day] = count; temp.update(); count ++; } int d, m, y; char s[20]; while(cin >> d >> s >> y) //此处注意对于格式的控制 { for(m = 1; m <= 12; m ++) if(strcmp(s, monthName[m]) == 0) break; int gap = buf[y][m][d] - buf[2016][11][21]; if(gap >= 0) cout << weekName[(gap % 7 + 1)] << endl; else cout << weekName[(gap % 7 + 7 + 1)] << endl; } return 0;}

总结

  1. day > daysOfMonth[month][ISLEAPYEAR(year)] 取数组元素的时候不要和函数混了
  2. 注意此题中数组的使用,很方便,另外数组的序号也很讲究

转载地址:http://skuin.baihongyu.com/

你可能感兴趣的文章
JAVA JVM 程序计数器(PC寄存器)
查看>>
JAVA虚拟机栈的主要特点
查看>>
JAVA虚拟机栈的常见异常与如何设置栈的大小
查看>>
JAVA JVM栈的存储单位
查看>>
JAVA JVM字节码指令集
查看>>
Java JVM栈帧的内部结构
查看>>
Java+OpenCV实现人脸抓拍并保存至本地
查看>>
JSONArray的使用
查看>>
设计模式
查看>>
Docker学习文档
查看>>
Docker指令
查看>>
URL连接外部接口工具类
查看>>
SpringBoot拦截器(新手快速使用)
查看>>
Git及GitHub快速上手
查看>>
Java JVM堆空间的概述
查看>>
mybatis+spring快速入门
查看>>
JWT之30分钟快速使用
查看>>
Linux开放端口报FirewallD is not running解决
查看>>
redis快速上手
查看>>
SpringCloud快速上手
查看>>