日期输入格式:X:Y:Z。如2017年1月1日——2017:1:1
实现思路:
- 把字符串转为整数
- 判断输入年份是平年还是闰年
- 计算天数
代码实现
// 字符串转整数函数
void stringToInt(char date[],int *year, int *month, int *day)
{
int i = 0;
// 判别年、月、日
// 0为年、1为月、2为日
int count = 0;
// 初始化年月日
*year = 0;
*month = 0;
*day = 0;
while(date[i] != '\0')
{
if(date[i] != ':')
{
// 字符转数字
int digit = date[i] - 48;
if(count == 0)
*year = *year * 10 + digit;
if(count == 1)
*month = *month * 10 + digit;
if(count == 2)
*day = *day * 10 + digit;
}
else
count += 1;
i++;
}
}
// 判断平年或闰年
int judge(int year)
{
// 0表示平年,1表示闰年
int flag = 0;
if(year % 100 != 0)
{
if(year % 4 == 0)
// 闰年
flag = 1;
else
// 平年
flag = 0;
}
else
{
if(year % 400 == 0)
// 闰年
flag = 1;
else
// 平年
flag = 0;
}
return flag;
}
// 计算天数函数
int calculate(int year, int month, int day)
{
if(month < 2)
return day;
else
{
int Feb = 0;
int flag = judge(year);
// 平年
if(flag == 0)
Feb = 28;
if(flag == 1)
Feb = 29;
switch(month)
{
case 2: return (31 + day);
case 3: return (31 + Feb + day);
case 4: return (31 * 2 + Feb + day);
case 5: return (31 * 2 + Feb + 30 + day);
case 6: return (31 * 3 + Feb + 30 + day);
case 7: return (31 * 3 + Feb + 30 * 2 + day);
case 8: return (31 * 4 + Feb + 30 * 2 + day);
case 9: return (31 * 5 + Feb + 30 * 2 + day);
case 10: return (31 * 5 + Feb + 30 * 3 + day);
case 11: return (31 * 6 + Feb + 30 * 3 + day);
case 12: return (31 * 6 + Feb + 30 * 4 + day);
}
}
}
整体实现
int mian()
{
// 时间数组
char date[20];
// 输入时间
scanf("%s",date);
// 定义年、月、日
int year = 0;
int month = 0;
int day = 0;
// 调用字符转整数函数
stringToInt(date, &year,&month, &day);
// 调用计算天数函数
int days = calculate(year,month,day);
// 打印结果
printf("%d\n",days);
return 0;
}