C++编写程序,给定一个日期,计算该日期是星期几。例如, 2023-05-19是星期五。 输入 第一行输入正整数n,表示输入的日期个数,1<=n<=100。 此后n行,每行输入一个日期的年月日三个数。 输出 每个日期是星期几。
时间: 2023-12-06 09:41:06 浏览: 122
以下是C++代码实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
int year, month, day;
cin >> year >> month >> day;
int days[] = {31,28,31,30,31,30,31,31,30,31,30,31}; //每个月的天数
int sum = 0;
for (int i = 0; i < month - 1; i++) {
sum += days[i];
}
sum += day;
if (month > 2 && (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)) {
sum += 1; //闰年二月加一天
}
int week = (sum + year - 1 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400) % 7; //蔡勒公式
switch (week) {
case 0: cout << "Sunday" << endl; break;
case 1: cout << "Monday" << endl; break;
case 2: cout << "Tuesday" << endl; break;
case 3: cout << "Wednesday" << endl; break;
case 4: cout << "Thursday" << endl; break;
case 5: cout << "Friday" << endl; break;
case 6: cout << "Saturday" << endl; break;
}
}
return 0;
}
```
这里用到了蔡勒公式来计算星期几,具体可以参考百度百科:https://baike.baidu.com/item/%E8%94%A1%E5%8B%92%E5%85%AC%E5%BC%8F/5180911?fr=aladdin
阅读全文