Based on Zeller's formula, only January and February have different results than expected.

Asked 2 years ago, Updated 2 years ago, 36 views

If you enter the year, month, and day respectively, I would like to create a program that prints the days of the week using the Zeller formula, but the results of the January and February run are as follows:

I created the program as follows

#include<stdio.h>
int main (void)
{
    int year, m, q, k, j, h;

    printf("year:");
    scanf("%d", & year);
    printf("Month:");
    scanf("%d", & m);
    printf("Day:");
    scanf("%d", & q);
    k = year%100;
    j = year/100;
    h = (q+(m+1)*26)/10+k+k/4+j/4+5*j)%7;
   /* On or before October 14, 1582, */
    if(year<1582||year==1582&&(m<10||m==10&&q<=14)){
    printf("Not supported before October 14, 1582);
    }
    else if(h==1){
    printf("%4d year %2d month %2d day is Sunday\n", year, m, q);
    }
    else if(h==2){
    printf("%4d year %2d month %2d day is Monday\n", year, m, q);
    } 
    else if(h==3){
    printf("%4d year %2d month %2d day is Tuesday\n", year, m, q);
    }
    else if(h==4){
    printf("%4d year %2d month %2d day is Wednesday\n", year, m, q);
    }
    else if(h==5){
    printf("%4d year %2d month %2d day is Thursday\n", year, m, q);
    }
    else if(h==6){
    printf("%4d year %2d month %2d day is Friday\n", year, m, q);
    } 
    else if(h==0){
    printf("%4d year %2d month %2d day is Saturday\n", year, m, q);
    }
    return 0;
}

Run Results

$./a.out
Year: 2020
Month: 2
Day: 7
February 7th, 2020 is Wednesday.

$ ./a.out
Year: 2020
Month: 1
Day: 31
January 31st, 2020 is Thursday.

$ ./a.out
Year: 2020
Month: 3
Day: 7
March 7th, 2020 is Saturday.

$ ./a.out
Year: 2020
Month: 4
Day: 6
April 6th, 2020 is Monday.

As you can see, the output for the days of the week after March is correct, but for some reason, January and February are incorrect.

Why does this happen?
Also, where should I correct to make the display correct?

Thank you for your cooperation.

c

2022-09-30 19:24

2 Answers


2022-09-30 19:24

Why does this happen?

I can't do +1 in January and February of the leap year, can I?


2022-09-30 19:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.