天天看點

C Primer Plus 14章第二題

編寫一個函數,提示使用者輸入日、月和年。月份可以是月份号、月分名或月分名縮寫。然後該程式應傳回一年中到使用者指定日子(包括這一天)的總天數。

#include <stdio.h>

#include <string.h>

typedef struct mon

{

char months[10];

char month_s[10];

int days;

}MONTH;

int main()

{

int sum_s = 0;

sum_s = sum();

printf(“你輸入的日期總天數是:%d\n”,sum_s);

system(“pause”);

return 0;

}

int sum()

{

int month_s,year,day,i,day_sum = 0;

char month[10];

MONTH months[12] = { //初始化結構數組

{“january”,“jan”,31},

{“february”,“feb”,28},

{“march”,“mar”,31},

{“april”,“apr”,30},

{“may”,“may”,31},

{“june”,“jun”,30},

{“july”,“jul”,31},

{“august”,“aug”,31},

{“september”,“sept”,30},

{“october”,“sept”,31},

{“november”,“nov”,30},

{“december”,“dec”,31}

};

printf(“輸入年份:”);

scanf("%d",&year);

printf(“輸入月:”);

while(1)

{

while(scanf("%d",&month_s) != 1)//判斷輸入的是數字還是字元串

{

gets(month);//儲存字元串

for(month_s = 1;month_s <= 12;month_s++)//用循環增加month_s變量,month_s代表月份

{

if(strcmp(month,months[month_s - 1].months) == 0||strcmp(month,months[month_s - 1].month_s) == 0)//比較結構數組成員是否比對

break;

}

if(month_s == 13)

printf(“月份輸入有誤,請重新輸入!\n”);

else

break;

}

if(month_s == 0 || month_s > 12)//輸入月份為0或者大于12則重新循環

printf(“月份不能為0 或 大于12!\n”);

else

break;

}

printf(“輸入日:”);

while(1)

{

while(scanf("%d",&day) != 1)//輸入判斷隻能為數字

{

while(getchar() != ‘\n’)

continue;

}

if(year % 4 == 0)//如果該年份是閏年,把結構第二個元素的天數改為29

{

months[1].days = 29;

}

if(day > months[month_s - 1].days)//輸入的天數不能大于輸入月份的天數

printf(“天數不能大于目前月份天數!\n”);

else

break;

}

if(month_s == 1)//輸入的是1月直接加上天數

day_sum += day;

else

{

for(i = 0;i < month_s-1;i++)//循環加上輸入月數-1的天數和

{

day_sum += months[i].days;

}

day_sum += day;

}

return day_sum;

}

繼續閱讀