Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How should I create a batch file program that if I input a year the program will identify if it is a leap year or not.

@echo off
cls
echo.  LEAP YEAR
echo. Enter Year:
exit /b 0

Well, its just that i need help like suggestions to what should i do.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
335 views
Welcome To Ask or Share your Answers For Others

1 Answer

@echo off
setlocal

set /P "year=Enter year: "
set /A "leap=!(year%%4) + (!!(year%%100)-!!(year%%400))"
if %leap% equ 1 echo Is leap year

Accordingly to Wikipedia a year is leap if it is divisible by 4 excepting if it is also divisible by 100, in which case it is leap only if it is also divisible by 400 ("divisible" means that the remainder of the division by the given number is zero). This way, 2000 and 2400 are leap years because their remainders when they are divided by 400 are zero, but 2100, 2200 and 2300 are not: these are special cases because their remainders when they are divided by 100 are zero.

In set /A command the ! boolean NOT operator gives 1 if its operand is zero and gives 0 in any other case, so set /A "leap=!(year%%4)" gives 1 if the year is divisible by 4 and zero in any other case; this gives the first part of the result.

After that we need to subtract 1 from this value in years 2100, 2200 and 2300, but subtract nothing in years 2000 and 2400; that is:

year    year%%100    a=!!(year%%100)    year%%400    b=!!(year%%400)    a-b
2000    0              0                0              0                 0
2100    0              0                100            1                 -1
2200    0              0                200            1                 -1
2300    0              0                300            1                 -1
2400    0              0                0              0                 0

If the year is not divisible by 100 then both a and b values are equal to 1, so a-b is zero and the result is given just by the original remainder by 4.

This way, the formula set /A "leap=!(year%%4) + (!!(year%%100)-!!(year%%400))" gives the complete result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...