编写一个c程序:输入一个日期,输出该日期是本年的第几天。(用if实现)需要考虑今年是闰年,输入形式:用横线分割的日期,格式为yyyy-mm-dd,输出形式:一个整数,表示该日期为本年的第几天
时间: 2024-10-21 14:03:47 浏览: 40
编写一个C语言程序,可以按照您的需求进行操作。首先,我们需要判断是否是闰年,并处理用户输入的日期。以下是一个基本的示例代码:
```c
#include <stdio.h>
#include <stdbool.h>
// 判断是否是闰年
bool is_leap_year(int year) {
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
return true;
}
else {
return false;
}
}
// 计算一年中某一天是第几天
int day_of_year(int year, int month, int day) {
// 年初天数
int days_in_month[] = {0, 31, 59, is_leap_year(year) ? 91 : 60, 89, 119, 149, 179, 209, 239, 269};
int total_days = 0;
for (int i = 0; i < month - 1; i++) {
total_days += days_in_month[i];
}
total_days += day;
return total_days;
}
int main() {
char date[11];
printf("请输入日期(格式 yyyy-mm-dd): ");
scanf("%s", date);
// 分割日期
char* parts[] = {date, NULL};
int year, month, day;
sscanf(parts[0], "%d-%d-%d", &year, &month, &day);
// 检查日期有效性
if(month <= 0 || month > 12 || day <= 0 || day > 31) {
printf("无效的日期格式\n");
return 1;
}
// 输出结果
int day_of_current_year = day_of_year(year, month, day);
printf("该日期是本年的第%d天。\n", day_of_current_year);
return 0;
}
```
在这个程序中,我们首先定义了一个`is_leap_year()`函数来检查是否是闰年。然后,在`day_of_year()`函数中计算给定日期是一年中的第几天。在`main()`函数里,我们获取用户的输入并进行相应的计算。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)