【问题标题】:Find the index of the first day of the year (new year)查找一年中第一天的索引(新年)
【发布时间】:2017-10-16 16:15:42
【问题描述】:

我是一名新手程序员,正在尝试制作日历(作业的一部分)。我已经完成了所有其他工作,但在我发现新年的索引(从 0 到 6)的部分上卡住了,除了闰年之后的一年,它每年向右移动一个。对于这个特定的部分,我没有一个好的算法,所以我只是想了想。它可以计算并工作到 1800,但之后它就不能正常工作了。我不知道为什么。但这里是代码:

public static int indexOfNewYear (int month, int year){

    int count = 0;
    int modOfDays = 0;
    int numberOfDays = 365;

    year = year - 2; // starts with year 2 because index of New Year is 0

    for (int t = 1; t <= year; year--){

        if(year + 2 == 1753){ // year 1752 skipped 11 days ahead
            numberOfDays += 10;
        } 

        count = modOfDays + numberOfDays;
        modOfDays = count  % 7;     

        if((year + 1) %  4 == 0 && year != 1){ // leap year skips two indexes
            modOfDays += 1;
        }
    }

    //System.out.println("modOfDays: " + modOfDays);
    return modOfDays;
}

非常感谢任何帮助!

【问题讨论】:

  • 你知道你的闰年测试不完全正确吗?
  • for 循环中初始化一个您随后不更改其值的变量是不寻常的。 for (int t = 1; ...) -> t 始终为 1。

标签: java


【解决方案1】:

看看您是如何计算闰年的 - 如果您使用的是公历,闰年只发生在能被 4 整除的年份,除了能被 100 整除的年份,除非该年份也能被 400 整除。

因此,1900(能被 100 整除但不能被 400 整除)是平年,而 2000(能被 100 和 400 整除)是闰年。

将此逻辑应用于计算闰年的方式。

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    相关资源
    最近更新 更多