zeller的同余代码出错

Mic*_*ael 2 java

public static void main(String [] args)
{
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the month (1-12):");
    int month = input.nextInt();
    System.out.print("Enter the day (1-31):");
    int day = input.nextInt();
    System.out.print("Enter the year (ex. 2014):");
    int year = input.nextInt();

    if (month == 1)
        month = 13;
    else if (month == 2)
        month = 14;

    int Zeller = day + ((26 * (month + 1)) / 10) + year +
        (year / 4) + (6 * (year / 100)) + (year / 400);

    int dayofweek = (Zeller + 5) % 7 + 1;

     if (dayofweek == 1)
        System.out.print("Day of the week: Monday");
    else if (dayofweek == 2)
        System.out.print("Day of the week: Tuesday");
    else if (dayofweek == 3)
        System.out.print("Day of the week: Wednesday");
    else if (dayofweek == 4)
        System.out.print("Day of the week: Thursday");
    else if (dayofweek == 5)
        System.out.print("Day of the week: Friday");
    else if (dayofweek == 6)
        System.out.print("Day of the week: Saturday");
    else if (dayofweek == 7)
        System.out.print("Day of the week: Sunday");  
}
Run Code Online (Sandbox Code Playgroud)

代码不会正确计算1月和2月的日期.它总是一两天.

例如:如果我输入Jan 1, 2010代码应该输出Day of the week: Friday,而是说它的说法Day of the week: Saturday.

我检查过我的计算找不到任何错误.

rge*_*man 5

根据Zeller的同余维基页面,当您调整1月和2月的月份时,您还必须调整年份,因为算法依赖于1月和2月被认为是上一年的"第13"和"第14"月.

但是当使用计算机时,处理修改后的Y年(在1月和2月期间为Y - 1)更简单:

将年度调整代码添加到1月和2月的案例中.

if (month == 1)
{
    month = 13;
    year--;  // add this
}
else if (month == 2)
{
    month = 14;
    year--;  // add this
}
Run Code Online (Sandbox Code Playgroud)

2010年1月1日测试用例的输出:

Enter the month (1-12):1
Enter the day (1-31):1
Enter the year (ex. 2014):2010
Day of the week: Friday
Run Code Online (Sandbox Code Playgroud)

上述案例可以简化:

if (month == 1 || month == 2)
{
    month += 12;
    year--;
}
Run Code Online (Sandbox Code Playgroud)