您的位置:首页 > 编程语言 > C语言/C++

C++实现——由年月日推算是星期几

2016-04-07 19:17 239 查看
#include <iostream>
#include <string>
#include <cmath>

using namespace std;
/*
语法:result = weekday(int N, int M, int d)
参数:
N, M, d:年月日,例如:2003, 11, 4
返回值:0:星期天,1星期一……
注意:
需要cmath
适用于1582年10月15日之后, 因为罗马教皇格里高利十三世在这一天启用新历法.
*/
//给定年月日,输出当天是星期几
int weekday(int N, int M, int d)
{
int m, n, c, y, w;
m = (M - 2) % 12;
if (M >= 3) n = N; else n = N - 1;
c = n / 100;
y = n % 100;
w = (int)(d + floor(13 * m / 5) + y + floor(y / 4) + floor(c / 4) - 2 * c) % 7;
while (w<0) w += 7;
return w;
}

//测试函数
int main(){

int year, month, day;
string week[] = {"日","一","二","三","四","五","六"};
while (cin >> year >> month >> day){

cout << year << "年" << month << "月" << day << "日是星期" << week[weekday(year, month, day)] << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: