gpt4 book ai didi

c++ - 从日期计算一年中的第几天

转载 作者:太空狗 更新时间:2023-10-29 23:36:13 25 4
gpt4 key购买 nike

我需要计算给定日期的天数。一年有 366 天。但是每个月都有不同的值,我必须分配这些值。有没有比我现在的方法更快的方法?

#include<iostream>
using namespace std;
int main()
{
int day, month, year, dayNumber;

cout<< "Please enter the month, by numerical value:";
cin>> month;
cout<<"Please enter the day, by numerical value:";
cin>> day;
cout<<"Please enter the year, by numerical value:";
cin>> year;
if (month == 1)
{
dayNumber= day;
cout<< "Month;" << '\t'<< month << '\n'
<< "Day:"<<'\t'<< day<< '\n'
<< "Year:"<<'\t'<< year<<'\n'
<< "Day Number:"<< '\t'<< dayNumber<< endl;
}
else if(month==2)
{
dayNumber= day+31;
}
}

最佳答案

只需使用mktime:

tm date = {};
date.tm_year = year - 1900;
date.tm_mon = month - 1;
date.tm_mday = day;
mktime( &date );
dayNumber = date.tm_yday;

否则,您将需要一个二维表:

int daysToMonth[2][12] =
{
{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 },
{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 },
};

和一个函数:

bool isLeapYear( int year )
{
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

那么年日是:

daysToMonth[isLeapYear( year ) ? 1 : 0][month] + day;

关于c++ - 从日期计算一年中的第几天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19110675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com