给定两个日期,计算相差的天数。比如2010-1-1和2010-1-3相差2天。用C++
时间: 2024-05-06 11:21:18 浏览: 129
语言怎么实现?
可以用以下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Date {
int year;
int month;
int day;
};
int isLeap(int year) {
return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0));
}
int daysOfMonth(int year, int month) {
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeap(year)) {
return 29;
}
return days[month - 1];
}
int getDays(struct Date date) {
int days = 0;
for (int i = 1; i < date.year; i++) {
days += isLeap(i) ? 366 : 365;
}
for (int i = 1; i < date.month; i++) {
days += daysOfMonth(date.year, i);
}
return days + date.day;
}
int main() {
struct Date startDate, endDate;
printf("请输入起始日期(格式:年-月-日):");
scanf("%d-%d-%d", &startDate.year, &startDate.month, &startDate.day);
printf("请输入结束日期(格式:年-月-日):");
scanf("%d-%d-%d", &endDate.year, &endDate.month, &endDate.day);
int startDays = getDays(startDate);
int endDays = getDays(endDate);
int diff = abs(endDays - startDays);
printf("两个日期相差%d天。\n", diff);
return 0;
}
```
该代码定义了一个`Date`结构体表示日期,实现了`isLeap()`函数用于判断是否为闰年,`daysOfMonth()`函数用于计算一个月有多少天,`getDays()`函数用于计算一个日期是当年的第几天,最后用主函数输入两个日期并调用前面的函数得到相差的天数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)