C primier plus 结构与数据 14.18.2

编写一个程序,请求用户输入日,月,年。月份可以是月份号,月分名,月份缩写。然后程序返回一年中到给定日子的总天数。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

union month_n   //联和类型每次存储其选项列表中的 一个单独 的数据项类型。(月份的三种输入方式)
{
	int m_n;
	char m_full[10]; //精确到存储“位”,应包含'\0'。
	char m_abb[4];
};

struct input 
{
	int day_n;
	union month_n mon;//联和的变量mon。
	int year_n;
};

struct months //该结构主要用于匹配三种输入月份的方式。
{
	char name_full[10];
	char name_abb[4];
	int day;
	int name_n;
};
//初始化。
struct months mons[12] = //结构months的变量mons。
	{
		{"January","JAN",31,1},
		{"Febyuary","FEB",28,2},
		{"March","MAR",31,3},
		{"April","APR",30,4},
		{"May","MAY",31,5},
		{"June","JUN",30,6},
		{"July","JUL",31,7},
		{"August","AGU",31,8},
		{"September","SEP",30,9},
		{"October","OCT",31,10},
		{"November","NOV",30,11},
		{"December","DEC",31,12}
	};

int main(void)
{	
	struct input in;//结构input的变量in。
	int i;
	int tot_days = 0;
	char line[10];

	while(1)
	{
	puts("Input the day:");
	scanf("%d",&in.day_n);
	while(getchar() != '\n')
		continue;//清除剩余行。
	
	puts("Input the month:");
	if(scanf("%d",&in.mon.m_n)==1)//月份存入联和中。
	{
		if(!(in.mon.m_n > 0 && in.mon.m_n < 13))
		{
			puts("Month out of range!");
			exit(1);
		}
	}
	else
	{
		scanf("%s",line);
		if(strlen(line) > 3)//月份输入是全称。
		{
			strcpy(in.mon.m_full,line);
			for(i = 0;i < 12;i++)//进行月份匹配。
			{
				if(strcmp(mons[i].name_full,in.mon.m_full) == 0)
				{
					in.mon.m_n = i+1 ;
					break;
				}
			}
		}
		else if(strlen(line) == 3)//月份输入缩写。strlen()不包含'\0'。
		{
			strcpy(in.mon.m_abb,line);
			for(i = 0;i < 12;i++)
			{
				if(strcmp(mons[i].name_abb,in.mon.m_abb) == 0)
				{
					in.mon.m_n = i+1;
					break;
				}
			}
		}
	}

	puts("Input the year:");
	scanf("%d",&in.year_n);
	for(i = 0;i <in.mon.m_n-1;i++)//in.mon.m_n-1是因为搜索到哪个月匹配时,该月是不计入月份天数相加,相加的是输入的天数。(重要的是这种+1,-1可以匹配三种输入月份的方式)
		tot_days += mons[i].day;
	tot_days += in.day_n;

	if(in.mon.m_n >= 2 && (in.year_n % 4 == 0 || in.year_n % 100 ==0))//闰年。
		++tot_days;
	
	printf("total %d days\n",tot_days);

	i=0;
	tot_days=0;
	puts("Please enter next round:");
	}
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值