计算某年某月某日为星期几(默认1年1月1日为星期一)

这题需要我们对于输入的年月日计算出对应的星期几,对于日期的计算,我们需要考虑到闰年以及具体月份的天数 ,具体c++代码如下:

#include<iostream>
#include<string>
using namespace std;
//默认1年1月1日为星期一
int whatday(int year, int month, int day) {
	int ans = 0;
	for (int i = 1;i < year;i++)
	{
		if (i % 400 == 0 || (i % 100 != 0 && i % 4 == 0))
		{
			ans += 366%7;
			ans %= 7;
		}
		else {
			ans += 365%7;
			ans %= 7;
		}
	}
	for (int i = 1;i < month;i++)
	{
		if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12)
		{
			ans += 31%7;
			ans %= 7;
		}
		else if (i == 4 || i == 6 || i == 9 || i == 11)
		{
			ans += 30%7;
			ans %= 7;
		}
		else if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
		{
			ans += 29%7;
			ans %= 7;
		}
		else
		{
			ans += 28%7;
			ans %= 7;
		}
	}
	ans += (day - 1) % 7;
	ans %= 7;
	return ans;
}
string weekday[7] = { "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday" };

int main() {
	int year, month, day;
	cin >> year >> month >> day;
	cout << weekday[whatday(year, month, day)] << endl;
	return 0;
}

这里采用了暴力求解,通过2个for循环,先计算出到year年1月1日为星期几,再计算出year年month月1日为星期几,在最后求出具体year年month月day日为星期几

day-1是因为ans[0]为monday,所以需要-1对应星期数组里的元素

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值