计算日期到天数转换/华为机试(C/C++)

本文介绍了一种计算特定日期是一年中第几天的方法,通过判断是否为闰年并累加各月天数,最终得出精确的日期位置。代码采用C++实现,包括输入年月日,判断闰年和平年,以及计算总天数的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

根据输入的日期,计算是这一年的第几天。。

详细描述:

输入某年某月某日,判断这一天是这一年的第几天?。

接口设计及说明:

 /*****************************************************************************
 Description   : 数据转换
 Input Param   : year 输入年份
                Month 输入月份
                Day 输入天
                    
 Output Param  :
 Return Value  : 成功返回0,失败返回-1(如:数据错误)
 *****************************************************************************/
 public static int iConverDateToDay(int year, int month, int day)
 {
     /* 在这里实现功能,将结果填入输入数组中*/ 
     return 0;
 }
 
 /*****************************************************************************
 Description   : 
 Input Param   :
                    
 Output Param  :
 Return Value  : 成功:返回outDay输出计算后的第几天;
                                           失败:返回-1
 *****************************************************************************/
 public static int getOutDay()
 {
  return 0;
 }

输入描述:

输入三行,分别是年,月,日

输出描述:

成功:返回outDay输出计算后的第几天;
                                           失败:返回-1

示例1

输入

2012

12

31

输出

366

代码:

//第七十一题  计算日期到天数转换
#include<iostream>
using namespace std;
int month1[12]{ 31,28,31,30,31,30,31,31,30,31,30,31 };
int month2[12]{ 31,29,31,30,31,30,31,31,30,31,30,31 };
int main()
{
	int year, month, day;
	while (cin >> year >> month >> day)
	{
		if (month > 12 || month < 0)
		{
			cout << -1 << endl;
			continue;
		}	
		int flag;
		int total_day = 0;
		int kyear = year % 4;
		int kyear1 = year % 100;
		int kyear2 = year % 400;
		if (kyear !=0 || (kyear1 ==0 && kyear2!=0))
		{
			int iMax = month - 1;
			if (day > month1[iMax] || day <= 0)
			{
				cout << -1 << endl;
				continue;
			}
			for (int i = 0; i < iMax; i++)
				total_day += month1[i];
			total_day += day;
			cout << total_day << endl;
		}
		else
		{
			int iMax = month - 1;
			for (int i = 0; i < iMax; i++)
				total_day += month2[i];
			total_day += day;
			cout << total_day << endl;
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值