C++设计一个函数,将Julian历法表示的日期转换成月和日,如Mar 8(注意闰年的问题)。函数返回一个字符串,即转换后的月和日。如果参数有错,如天数为第370天,返回NULL指针,此时屏幕无打印输出。平台会对你编写的代码进行测试: 测试输入: 1998 33 预期输出: Feb 2 点击复制后,将打开C知道体验页
时间: 2023-06-08 15:03:56 浏览: 223
c++代码输入年月日,判断平年还是闰年并打印出那天是那年的第几天
5星 · 资源好评率100%
抱歉,我可以回答这个问题。以下是C语言代码实现:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* julian_to_date(int year, int num)
{
int is_leap_year = (year%4 == 0 && year%100 != 0) || year%400 == 0; //判断是否为闰年
int months[12] = {31,28+is_leap_year,31,30,31,30,31,31,30,31,30,31}; //每个月的天数
if(num > 365+is_leap_year || num < 1) //天数错误
return NULL;
int i = 0;
while(num > months[i]) //找到对应的月份
{
num -= months[i];
i++;
}
char *res = (char*)malloc(sizeof(char)*6); //分配字符串空间
char month[4];
switch(i)
{
case 0: strcpy(month,"Jan"); break;
case 1: strcpy(month,"Feb"); break;
case 2: strcpy(month,"Mar"); break;
case 3: strcpy(month,"Apr"); break;
case 4: strcpy(month,"May"); break;
case 5: strcpy(month,"Jun"); break;
case 6: strcpy(month,"Jul"); break;
case 7: strcpy(month,"Aug"); break;
case 8: strcpy(month,"Sep"); break;
case 9: strcpy(month,"Oct"); break;
case 10: strcpy(month,"Nov"); break;
case 11: strcpy(month,"Dec"); break;
}
sprintf(res,"%s %d",month,num); //格式化字符串
return res;
}
示例调用:
int main()
{
char* res = julian_to_date(1998,33);
if(res == NULL)
printf("NULL pointer");
else
printf("%s",res);
free(res);
return 0;
}
输出结果为:"Feb 2"
阅读全文