要编写一个程序来判断星期几,你可以根据不同的编程语言选择不同的方法。以下是几种常见编程语言的实现方法:
1. 使用条件判断
Python
```python
import datetime
def get_weekday(date_str):
date = datetime.datetime.strptime(date_str, '%Y-%m-%d')
weekdays = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
return weekdays[date.weekday()]
date_str = input("请输入日期(格式:YYYY-MM-DD): ")
print(get_weekday(date_str))
```
C语言
```c
include include char* get_weekday(int year, int month, int day) { struct tm tm = {0}; tm.tm_year = year - 1900; tm.tm_mon = month - 1; tm.tm_mday = day; return asctime(&tm) + 4; // +4 to skip the newline character } int main() { int year, month, day; printf("请输入年、月、日(格式:YYYY MM DD): "); scanf("%d %d %d", &year, &month, &day); printf("%d-%02d-%02d %s\n", year, month, day, get_weekday(year, month, day)); return 0; } ``` 2. 使用标准库函数 Python ```python import datetime def get_weekday(date_str): date = datetime.datetime.strptime(date_str, '%Y-%m-%d') return date.strftime('%A') date_str = input("请输入日期(格式:YYYY-MM-DD): ") print(get_weekday(date_str)) ``` C语言 ```c include include char* get_weekday(int year, int month, int day) { struct tm tm = {0}; tm.tm_year = year - 1900; tm.tm_mon = month - 1; tm.tm_mday = day; return asctime(&tm) + 4; // +4 to skip the newline character } int main() { int year, month, day; printf("请输入年、月、日(格式:YYYY MM DD): "); scanf("%d %d %d", &year, &month, &day); printf("%d-%02d-%02d %s\n", year, month, day, get_weekday(year, month, day)); return 0; } ``` 3. 使用日期时间库 Python ```python import datetime def get_weekday(date_str): date = datetime.datetime.strptime(date_str, '%Y-%m-%d') return date.strftime('%A') date_str = input("请输入日期(格式:YYYY-MM-DD): ") print(get_weekday(date_str)) ``` C语言 ```c include include char* get_weekday(int year, int month, int day) { struct tm tm = {0}; tm.tm_year = year - 1900; tm.tm_mon = month - 1; tm.tm_mday = day; return asctime(&tm) + 4; // +4 to skip the newline character } int main() { int year, month, day; printf("请输入年、月、日(格式:YYYY MM DD): "); scanf("%d %d %d", &year, &month, &day); printf("%d-%02d-%02d %s\n", year, month, day, get_weekday(year, month, day)); return 0; } ``` 总结 以上代码展示了如何使用不同编程语言来判断给定日期是星期几。你可以根据自己的需求和熟悉程度选择合适的方法。Python的`datetime`模块和C语言的`time`模块都是处理日期和时间的常用工具。