用C++写一个程序,判断某年某月某日是星期几
时间: 2024-09-10 21:12:08 浏览: 54
在C++中,我们可以使用Zeller's congruence算法或者直接依赖于C库(如`<ctime>`)来计算某年某月某日是星期几。这里是一个简单的Zeller's congruence的例子,它不需要依赖外部库:
```cpp
#include <iostream>
// Zeller's Congruence function to calculate day of the week
int getDayOfWeek(int year, int month, int day) {
if (month < 3) {
month += 12;
year--;
}
int century = year / 100;
int year_of_century = year % 100;
int day_of_week = (day + 13 * (month + 1) / 5 + year_of_century + year_of_century / 4 + century / 4 + 5 * century) % 7;
// Convert numbers from 0-6 to corresponding weekday names (0 is Sunday)
switch (day_of_week) {
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
}
}
int main() {
int year, month, day;
std::cout << "Enter a date in format (YYYY MM DD): ";
std::cin >> year >> month >> day;
std::string dayOfWeek = getDayOfWeek(year, month, day);
std::cout << "The date " << year << "-" << month << "-" << day << " is " << dayOfWeek << "." << std::endl;
return 0;
}
```
当你运行这个程序并输入特定日期,它会告诉你那天是星期几。记得Zeller's congruence只适用于公元后的日期。
阅读全文