通过日期计算星期函数(C语言版)

测试源代码:

#include 

int getDayOfWeek(int year, int month, int day) {
    if (month < 3) {
        month += 12;
        year--;
    }

    int q = day;
    int m = month;
    int K = year % 100;
    int J = year / 100;

    int dayOfWeek = (q + 13 * (m + 1) / 5 + K + K / 4 + J / 4 - 2 * J) % 7;

    // Adjust for C's modulo operation that can result in negative values
    if (dayOfWeek < 0) {
        dayOfWeek += 7;
    }

    // 0 corresponds to Saturday, 1 to Sunday, ..., 6 to Friday
    return dayOfWeek;
}

int main() {
    int year, month, day;

    // Input date
    printf("Enter year: ");
    scanf("%d", &year);
    printf("Enter month: ");
    scanf("%d", &month);
    printf("Enter day: ");
    scanf("%d", &day);

    // Calculate day of week
    int dayOfWeek = getDayOfWeek(year, month, day);

    // Display the result
    switch (dayOfWeek) {
        case 0:
            printf("Saturday\n");
            break;
        case 1:
            printf("Sunday\n");
            break;
        case 2:
            printf("Monday\n");
            break;
        case 3:
            printf("Tuesday\n");
            break;
        case 4:
            printf("Wednesday\n");
            break;
        case 5:
            printf("Thursday\n");
            break;
        case 6:
            printf("Friday\n");
            break;
        default:
            printf("Invalid day\n");
            break;
    }

    return 0;
}

注意:其中0表示星期六,1表示星期天,以此类推。

你可能感兴趣的:(c语言,算法,开发语言)