1.简介
本文将解决一个c语言结构体相关问题,以此增加对结构体的认识以及c语言综合能力。
2.问题与构思
编写一个程序,提示用户输入日期,月和年。月份可以是月份号,月份名或月份名的缩写。然后程序返回一年中用户指定日子(包括这一天)为止的总天数。
首先,全年十二个月份,年,日的表示可以使用数组,并且月份要求能输入月份名等字符,故选择结构数组来储存不同类型数据。
运算函数利用逻辑语句和循环即可累加日数,利用指针跨函数传递变量信息。
最后合理安排输入输出即可。
3.编写程序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct month {
char month_name[10];
char month_abbrev[4];
int days;
int number;
} 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}
};
int cala_days(char* month, int day);
int main(int argc, char* argv[])
{
int year, day;
char month[10];
int result;
printf("Enter the year month day:");
scanf("%d %s %d", &year, month, &day);
while (1)
{
result = cala_days(month, day);
if (result < 0)
printf("Error input,retry.\n");
else
printf("The %d/%s/%d is %d days.\n", year, month, day, result);
printf("Enter the year month day:");
scanf("%d %s %d", &year, month, &day);
};
return 0;
}
int cala_days(char* month, int day)
{
int i;
if ((day < 1) || (day > 31))return -1;
int total = 0;
int temp = atoi(month);
for (i = 0; i < 12; i++)
{
if ((temp == months[i].number) || (strcmp(month, months[i].month_abbrev) == 0) || (strcmp(month, months[i].month_name) == 0))
{
if (day > months[i].days)return -1;
return total + day;
}
else total += months[i].days;
}
return -1;
}
以上即是实际程序编写。