Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

windows - Batch file leap year?

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

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

1 Reply

0 votes
by (71.8m points)
@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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...