# how to identify leap years

조회 수: 35 (최근 30일)
Anisia a 2020년 5월 18일
답변: Siva Charan 2023년 9월 30일
Hi,
I am trying to create a function that takes 3 +ve integer scalar inputs year, month and date. If these 3 represent a valid date return true otherwise return false. My code is running for most of the input. But I am having problem with leap years. The code I wrote is given below. Can anyone please point out my mistake.
function valid= valid_date(year, month, date)
v=1;
a= mode(year,4);
b= mode(year,100);
c= mode(year,400);
if ~isscalar(year) || year<1 || year~=fix(year) || ~isscalar(month) || month<1 || month~=fix(month) ||~isscalar(date)|| date<1 || date~=fix(date)
v= 0;
end
if v==0
valid=false;
return
end
if 0>month || month>12
v= 0;
elseif (month==1 ||month==3|| month==5 || month==7 || month==8|| month==10|| month==12)
if 0<date&& date<=31
v=1;
else
v=0;
end
elseif (month== 4 ||month==6|| month==9 || month==11)
if 0<date&& date<31
v=1;
else
v=0;
end
elseif month==2
if date==29
if (a==0 && b~=0) || c==0
v=1;
else
v=0;
end
elseif 0<date && date<29
v=1;
else
v=0;
end
end
if v==0
valid=false;
else
valid=true;
end

댓글을 달려면 로그인하십시오.

### 답변 (2개)

Siva Charan 2023년 9월 30일
Use this subfunction and call from the main function.
if the year is divisible by 100 and not divisible by 400, it is not a leap year. millennium years(1600, 1700, 1800...) should be divisible by 400 to be leap years, for others, any year that is divisible by 4 can be a leap year.
function leapyear = checkleap(year)
if mod(year,100)==0
if mod(year,400)==0
leapyear = true;
else
leapyear = false;
end
elseif mod(year,4) == 0
leapyear = true;
else
leapyear = false;
end
end
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

댓글을 달려면 로그인하십시오.

Stijn Haenen 2020년 5월 18일
편집: Stijn Haenen 2020년 5월 18일
There is a leap year every four years, so you can use this:
if mod(year,4)==0
'leap year'
else
'not a leap year'
end
##### 댓글 수: 4이전 댓글 2개 표시이전 댓글 2개 숨기기
Stephen23 2020년 5월 18일
These are all divisible by four: 1500, 1700, 1800, 1900, 2100, 2200, 2300, 2500, but none of them are leap years.
Steven Lord 2020년 5월 18일
Yes. The Wikipedia page has the algorithm for how to determine whether a year is a leap year.

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Calendar에 대해 자세히 알아보기

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by