c语言中 如何判断输入的c语言输入年月日判断哪一天是否合规?

题目:输入某年某月某日,判断这一天是这一年的第几天?分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需多加一天。普通方法:int main() {
int year, month, day;
printf("请输入年.月.日:");
scanf("%d.%d.%d", &year, &month, &day);
switch (month) {
case 1:break; // 1月输入第几号,就是本年第几天
case 2:day += 31;break; // 这里直接用day存储的天数
case 3:day += 59;break;
case 4:day += 90;break;
case 5:day += 120;break;
case 6:day += 151;break;
case 7:day += 181;break;
case 8:day += 212;break;
case 9:day += 243;break;
case 10:day += 273;break;
case 11:day += 304;break;
case 12:day += 334;break;
default:printf("data error");break;
}
// 判断当年是否为闰年,若为闰年,3月以后的天数都加1
if ((year % 4 == 0 && year % 100 != 0)
year % 400 == 0) {
if (month >= 3) {
day++;
}
}
printf("是%d年的第%d天\n", year, day);
return 0;
}
结构体:int main() {
struct Date {
int year;
int month;
int day;
}date;
int total; // 记录总天数
printf("请输入年.月.日:");
scanf("%d.%d.%d", &date.year, &date.month, &date.day);
switch (date.month) {
case 1:break; // 1月输入第几号,就是本年第几天
case 2:total = 31;break; // 2月时,暂时存储2月前的总天数,即一月的天数,以下同理
case 3:total = 59;break;
case 4:total = 90;break;
case 5:total = 120;break;
case 6:total = 151;break;
case 7:total = 181;break;
case 8:total = 212;break;
case 9:total = 243;break;
case 10:total = 273;break;
case 11:total = 304;break;
case 12:total = 334;break;
default:printf("data error");break;
}
total += date.day;//total在加上当月的天数
// 判断当年是否为闰年,若为闰年,3月以后的天数都加1
if ((date.year % 4 == 0 && date.year % 100 != 0)
date.year % 400 == 0) {
if (date.month >= 3) {
total++;
}
}
printf("%d.%d.%d是%d年的第%d天\n", date.year,date.month,date.day,date.year, total);
return 0;
}
运行效果:}

我要回帖

更多关于 c语言输入年月日判断哪一天 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信