练习7-9 计算天数 (15分)
代码:
#include <stdio.h>
int main()
{
char date[10];
scanf("%s", &date);
int totalDay = 0;
int i = 0, year = 0, month = 0, day = 0;
for (i = 0; i < 4; i++) year = year * 10 + (date[i] - '0');
for (i = 5; i < 7; i++) month = month * 10 + (date[i] - '0');
for (i = 8; i < 10; i++) day = day * 10 + (date[i] - '0');
switch(month) {
case 1: totalDay = 0; break;
case 2: totalDay = 31; break;
case 3: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 60;
else totalDay += 59;
break;
}
case 4: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 91;
else totalDay += 90;
break;
}
case 5: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 121;
else totalDay += 120;
break;
}
case 6: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 152;
else totalDay += 151;
break;
}
case 7: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 182;
else totalDay += 181;
break;
}
case 8: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 213;
else totalDay += 212;
break;
}
case 9: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 244;
else totalDay += 243;
break;
}
case 10: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 274;
else totalDay += 273;
break;
}
case 11: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 305;
else totalDay += 304;
break;
}
case 12: {
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) totalDay = 335;
else totalDay += 334;
break;
}
}
printf("%d", totalDay + day);
return 0;
}