C语言。编写程序,解决两个方向日期转换问题,实现要求如下: (1)屏幕菜单提示信息如下: 1.year/month/day->yearday 2.year/yearday->year/month/day 3.Exit 根据以上输入1、2、3选项分别完成不同功能,如果输入错错误,应提示相应的出错信息。 (2)实现unsigned int Dayofyear(unsigned int year,unsigned int month,unsigned int day)函数,完成将年、月、日信息转换为该年中的总天数,即参数为年月日,返回值为天数。 (3)实现void MonthandDay(unsigned int year,unsigned int totolday,unsigned int * month,unsigned int * day)函数,完成将年、总天数转换为对应的月、日,月份和日期信息通过指针返回。
时间: 2024-02-15 10:06:06 浏览: 82
c语言实现的任意日期和天数的转换
3星 · 编辑精心推荐
好的,以下是代码实现:
```c
#include <stdio.h>
// 计算该年中的总天数
unsigned int Dayofyear(unsigned int year, unsigned int month, unsigned int day) {
unsigned int dayTab[2][13] = {
{0,31,59,90,120,151,181,212,243,273,304,334,365},
{0,31,60,91,121,152,182,213,244,274,305,335,366}
};
int leap = (year%4==0 && year%100!=0) || year%400==0;
return dayTab[leap][month-1] + day;
}
// 将总天数转换为月份和日期
void MonthandDay(unsigned int year, unsigned int totolday, unsigned int *month, unsigned int *day) {
unsigned int dayTab[2][13] = {
{0,31,59,90,120,151,181,212,243,273,304,334,365},
{0,31,60,91,121,152,182,213,244,274,305,335,366}
};
int leap = (year%4==0 && year%100!=0) || year%400==0;
int i;
for (i = 1; i <= 12; i++) {
if (totolday <= dayTab[leap][i]) {
*month = i;
*day = totolday - dayTab[leap][i-1];
break;
}
}
}
int main() {
unsigned int year, month, day, yearday, option;
unsigned int totolday, ret_month, ret_day;
while (1) {
printf("1.year/month/day->yearday\n");
printf("2.year/yearday->year/month/day\n");
printf("3.Exit\n");
printf("Please enter option: ");
scanf("%u", &option);
if (option == 1) {
printf("Please enter year, month, day (separated by spaces): ");
scanf("%u %u %u", &year, &month, &day);
yearday = Dayofyear(year, month, day);
printf("%u/%u/%u is the %u day of %u\n", year, month, day, yearday, year);
} else if (option == 2) {
printf("Please enter year, yearday: ");
scanf("%u %u", &year, &totolday);
MonthandDay(year, totolday, &ret_month, &ret_day);
printf("%u year %u day is %u/%u/%u\n", year, totolday, year, ret_month, ret_day);
} else if (option == 3) {
break;
} else {
printf("Invalid option!\n");
}
}
return 0;
}
```
这个程序实现了一个菜单,让用户选择日期转换的功能。当用户选择 1 时,程序会要求用户输入年、月、日,然后计算出该日期是该年的第几天。当用户选择 2 时,程序会要求用户输入年和该年的第几天,然后计算出对应的月份和日期。当用户选择 3 时,程序会退出。
注意,为了方便起见,这里假设所有输入都是正确的,没有做输入检查。如果需要更加健壮的程序,需要加上输入检查的代码。
阅读全文