Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

วิธีหาปีอธิกสุรทิน (Leap Year) โดยใช้ภาษา C


ปีอธิกสุรทิน (Leap Year) คือปีที่มี 366 วัน ทุก 4 ปี จะมีปีอธิกสุรทิน 1 ครั้ง

ตรรกะที่ใช้ตรวจสอบว่าปีที่ผู้ใช้ป้อนผ่านคอนโซลเป็นปีอธิกสุรทินหรือไม่:

if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))

หากเงื่อนไขนี้เป็นจริง ปีที่กำหนดเป็นปีอธิกสุรทิน มิฉะนั้นไม่ใช่

ตัวอย่าง

โปรแกรม C ตรวจสอบปีอธิกสุรทิน ด้วยเงื่อนไข if:

#include <stdio.h>

int main() {
    int year;
    printf("Enter any year you wish \n");
    scanf(" %d ", &year);
    
    if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
        printf("\n %d is a Leap Year. \n", year);
    else
        printf("\n %d is not the Leap Year. \n", year);
    
    return 0;
}

ผลลัพธ์

เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:

Enter any year you wish 2045
2045 is not the Leap Year.