在检测闰年方面有问题
Having problems with detecting leap year
avHi,感谢大家在我之前的问题上给予的帮助。
然而,现在我遇到了另一个问题
int main ()
{
int inputSeconds,seconds, minutes, hours , days ,years ;
int remainingSeconds ;
int current_year = 1970;
int current_month = 1;
int current_day = 1;
const int standard_year = 365;
const int leap_year = 366;
bool leapYear;
int leapcounter ; //Since 1972 is the next closest leap year, counter is set to 2
cout << "Welcome to Epoch time/ Data converter" << endl;
cout << "Enter Number of Seconds Since Midnight Jan 1, 1970: ";
cin >> inputSeconds ;
//Convert seconds into days to determine the number of years that has already passed
days = inputSeconds/(60*60*24) ;
remainingSeconds = inputSeconds % (60*60*24) ;
cout << days << endl;
//Determine current year
while (!(days < 365))
{
if (leapcounter == 3 )
{
current_year++;
days -= leap_year;
leapYear = true;
leapcounter = 0;
}
else
{
current_year++;
days -= standard_year;
leapcounter++;
leapYear = false;
}
}
//Check if current year is leap year or not
if ((current_year % 4 == 0) && (current_year % 100 == 0) || (current_year % 400 == 0))
leapYear = true;
else
leapYear = false;
cout << current_year << " days remaining :" << days << " Leap year? " << leapYear << " Remaining seconds :" << remainingSeconds;
return 0;
}
它似乎没有发现产量出现闰年。我试过1972年、2004年、2008年和2012年。
我似乎弄不清这个问题,希望你能帮我解决这个问题提前谢谢。
从current_year
决定闰年的逻辑比现有的要复杂一些。
它需要:
if ((current_year % 4 == 0) )
{
if ( (current_year % 100 == 0) )
{
if ( (current_year % 400 == 0) )
{
leapYear = true;
}
else
{
leapYear = false;
}
}
else
{
leapYear = true;
}
}
else
{
leapYear = false;
}
进一步思考,这种逻辑可以简化为:
leapYear = ( (current_year % 400) == 0 ||
( (current_year % 4) == 0 && (current_year % 100) != 0)) ;
此外,您需要将leapcounter
初始化为2
,因为1
对应于1970
的第一天——自上一个闰年以来的2年。
开始:
bool IsALeapYear(int year) {
return (!(year % 4) && (year % 100)) || !(year % 400);
}
相关文章:
- 我似乎对if/else的基本语句有问题:/
- 我在范围内未声明的错误类有问题
- 我的C++语言蛮力算法有问题
- 我关于函数"Assert"的C++代码有问题
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- C++类中的友元函数有问题?
- 我对数组即 0x6dfe78 有问题
- 我对 std::unique(算法)C++有问题
- 使用 fstream 库并在屏幕上打印的文件有问题?
- 这个模板为什么有问题?如何正确编译
- 我对 MyGraph 属性顶点名称和边权重有问题
- delete[]有问题,如何部分删除内存
- 在C++中使用exit()退出程序有问题吗
- 跳转到if(false)块有问题吗
- 查找有问题的宏
- 使用 rand() 和 srand() 有问题
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 我在 C++ "out_of_range at memory location"有问题
- 二叉搜索树在插入功能方面有问题
- 在检测闰年方面有问题