给出年、月、日,计算该日是该年的第几天

C程序设计(第五版)谭浩强著,第七章练习第18题

求该日是该年的第几天,按照生活中的一般思路,就是把那天所在月份之前的月份的天数全部相加,随后在加上该月份的天数days。

在此基础上,再考虑是否为闰年,是否包含了二月份。

#include<stdio.h>
int main()
{
	int count(int y, int m, int d);
	int year, month, day, i;
	printf("请输入年,月,日:");
	scanf_s("%d,%d,%d", &year, &month, &day);
	i = count(year, month, day);
	printf("是这一年的第%d天", i);
	return 0;
}

int count(int y, int m, int d)
{
	int i=0;
	if (m == 1)
		i = d;
	if (m == 2)
		i = 31 + d;
	if (m == 3)
		i = 31 + 28 + d;
	if (m == 4)
		i = 31 + 28 + 31 + d;
	if (m == 5)
		i = 31 + 28 + 31 + 30 + d;
	if (m == 6)
		i = 31 + 28 + 31 + 30 + 31 + d;
	if (m == 7)
		i = 31 + 28 + 31 + 30 + 31 + 30 + d;
	if (m == 8)
		i = 31 + 28 + 31 + 30 + 31 + 30 + 31 + d;
	if (m == 9)
		i = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + d;
	if (m == 10)
		i = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + d;
	if (m == 11)
		i = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + d;
	if (m == 12)
		i = 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + d;
	if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
	{
		if (m > 2)
			i = i + 1;
	}
	return (i);
}

 

 

但是这个程序在写的过程中就发现简单的问题太过繁琐。

#include<stdio.h>
int main()
{
	int count(int y, int m, int d);
	int year, month, day, i;
	printf("请输入年,月,日:");
	scanf_s("%d,%d,%d", &year, &month, &day);
	i = count(year, month, day);
	printf("是这一年的第%d天", i);
	return 0;
}

int count(int y, int m, int d)
{
	int i = 0,j=0,n;
	int a[12] = { 0,31,28,31,30,31,30,31,31,30,31,30 };
	for (n = 0; j < m; j++)
	{
		n = n + a[j];
	}
	i = n + d;
	if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
	{
		if (m > 2)
			i = i + 1;
	}
	return (i);
}

将数组运用其中,就精简一些啦。

  • 11
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值