编写—个程序。请求用户键入日、月和年。月份可以是月份号、月份名或月份缩写。然后程序返回一年中到给定日子(包括这一天)的总天数

C Primr Plus 第14章第2题,网上没有找到太好的解答。找到的几个答案都没有考虑到月份的几个不同的输入形式,于是自己简单写了下,偷懒没有对输入的条件进行判断,可以自己添加一下。

#include

#include
#include
//14.2


typedef struct 
{
char month_name[10];
char month_abbre[4];
int day;
int month_num;
}month;




void eatline();
void modify(month *, int);
int getmon_num(char *,month *);
int countdays(month *, int, int);
int main()
{
int day, year,mon_num,totaldays;
char mon[10];
month months[12] = 
{
{ "january", "jan", 31, 1 },
{ "february", "feb", 28, 2 },
{ "march", "mar", 31, 3 },
{ "april", "apr", 30, 4 },
{ "may", "may", 31, 5 },
{ "june", "jun", 30, 6 },
{ "july", "jul", 31, 7 },
{ "august", "aug", 31, 8 },
{ "september", "sep", 30, 9 },
{ "october", "oct", 31, 10 },
{ "november", "nov", 30, 11 },
{ "december", "dec", 31, 12 }
};
month *pr = &months;
printf("enter your day:");
scanf("%d", &day);
printf("enter your mon:");
scanf("%s", mon);
eatline();
printf("enter your year:");
scanf("%d", &year);
eatline();
modify(pr, year);%确定是不是闰年,如果是的话对months数组内第二月份的值进行调整
mon_num = getmon_num(mon,pr);%输入月份的字符串形式,得到对应的月份的int数值
totaldays = countdays(pr, mon_num, day);%计算总的天数
printf("total days is %d", totaldays);
return 0;
}


void eatline()
{
while (getchar() != '\n')
{
continue;
}
}


void modify(month *pr, int year)
{
if (year % 400 == 0)
(pr + 1)->day = 29;
else if (year % 4 == 0 && year % 100 == 0)
(pr + 1)->day = 29;
else
;
}


int getmon_num(char *str,month *pr)
{
int i;
if (atoi(str) != 0)
return atoi(str);
else
for (i = 0; i < 12; i++)
{
if (strcmp(str, pr->month_name) == 0 || strcmp(str, pr->month_abbre) == 0)
return i+1;
else
pr++;
}
}


int countdays(month *pr, int month, int day)
{
int i, totaldays=0;
for (i = 0; i < month - 1; i++)
{
totaldays += pr->day;
pr++;
}
totaldays += (day-1);
return totaldays;
}

你可能感兴趣的:(C语言课后习题,c)