c语言结构体实际运用

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;

	}


以上即是实际程序编写。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值