输入一个日期,输出那一天是星期几。 目前已知: 1960−01−01为星期五; 2000−01−01为星期六; 2040−01−01为星期日; 2080−01−01为星期一。 c++代码求答案
时间: 2024-09-18 22:17:25 浏览: 52
在C++中,你可以使用`<chrono>`库来处理日期时间并计算星期几。下面是一个简单的函数示例,它基于给定的信息来推算任意日期的星期:
```cpp
#include <iostream>
#include <chrono>
// 定义转换天数到星期的辅助函数
std::string day_of_week(int year, int month, int day) {
// 使用Zeller's congruence公式来计算星期
int q = day;
int m = (month > 2) ? month : (month + 12);
int k = year % 100;
int j = year / 100;
int h = (q + ((m + 13 * ((j - 1) / 4)) + 5 * j + (k + (k / 4))) % 7);
switch (h) {
case 0: return "星期日";
case 1: return "星期一";
case 2: return "星期二";
case 3: return "星期三";
case 4: return "星期四";
case 5: return "星期五";
case 6: return "星期六";
default: throw std::runtime_error("Invalid date");
}
}
int main() {
int year, month, day;
std::cout << "请输入年月日(例如:2023 12 31): ";
std::cin >> year >> month >> day;
try {
std::cout << "那一天是:" << day_of_week(year, month, day) << std::endl;
} catch (const std::runtime_error& e) {
std::cerr << "错误: " << e.what() << std::endl;
}
return 0;
}
```
这个程序首先获取用户输入的年月日,然后通过Zeller's congruence算法计算对应的星期,并返回相应的字符串表示。注意,这只是一个基础实现,实际应用中可能需要更全面的日历处理库,如`<ctime>`或第三方库。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)