定义一个满足如下要求的Date类 用下列的数据输出数据 年-月-日 输入格式: 年 月 日 例如 1978 5 2 2020 12 12 输出格式: 1978-05-02 2020-12-12
时间: 2024-01-10 13:04:47 浏览: 138
以下是满足要求的Date类的定义和示例代码:
```python
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def format_date(self):
formatted_month = str(self.month).zfill(2)
formatted_day = str(self.day).zfill(2)
return f"{self.year}-{formatted_month}-{formatted_day}"
# 示例数据
date1 = Date(1978, 5, 2)
date2 = Date(2020, 12, 12)
# 输出结果
print(date1.format_date())
print(date2.format_date())
```
运行以上代码将输出:
```
1978-05-02
2020-12-12
```
这个Date类有一个构造函数 `__init__`,用于初始化年、月和日的属性。`format_date` 方法用于将日期格式化为指定的输出格式。在示例中,我们创建了两个Date对象,并调用了它们的 `format_date` 方法来输出格式化后的日期。
相关问题
定义一个满足如下要求的Date类 用下列的数据输出数据 年-月-日 输入格式: 年 月 日 例如 1978 5 2 2020 12 12 输出格式: 1978-05-02 2020-12-12
```python
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __str__(self):
return "{:04d}-{:02d}-{:02d}".format(self.year, self.month, self.day)
date1 = Date(1978, 5, 2)
date2 = Date(2020, 12, 12)
print(date1) # 1978-05-02
print(date2) # 2020-12-12
```
用C++定义一个满足如下要求的Date类 用下列的数据输出数据 年-月-日 输入格式: 年 月 日 例如 1978 5 2 2020 12 12 输出格式: 1978-05-02 2020-12-12
```c
#include <stdio.h>
// Date类的定义
typedef struct {
int year;
int month;
int day;
} Date;
int main() {
// 定义两个Date类的实例
Date date1, date2;
// 输入年月日
scanf("%d %d %d", &date1.year, &date1.month, &date1.day);
scanf("%d %d %d", &date2.year, &date2.month, &date2.day);
// 格式化输出
printf("%04d-%02d-%02d\n", date1.year, date1.month, date1.day);
printf("%04d-%02d-%02d\n", date2.year, date2.month, date2.day);
return 0;
}
```
阅读全文
相关推荐














