Need help on this program

조회 수: 2 (최근 30일)
Sri Thota
Sri Thota 2021년 12월 28일
댓글: Sri Thota 2021년 12월 29일
My code is working for all random inputs, except for valid_date(2002,2,28). Could somebody please suggest? Thank you
function valid = valid_date(year,month,day)
if ((isscalar(year) && year>0 ) && (isscalar(month) && month>0) && (isscalar(day) && day>0))
%For Leap year
if (((rem(year,4) == 0) && (rem(year,100) == 0) && (rem(year,400) == 0)) || ((rem(year,4) == 0) && (rem(year,100) ~= 0)))
valid_leap = true;
else
valid_leap = false;
end
% check for february
if(valid_leap == true && month==2 && day <=29)
valid = true;
else if(valid_leap == false && month==2 && day <=28)
valid = true;
else
valid = false;
end
% check for other months
if (month==1 || month==3 || month==5 || month==7 || month==8 || month ==10 || month==12) && (day <= 31)
valid = true;
elseif (month==4 || month==6 || month==9 || month==11) && (day <= 30)
valid = true;
else
valid = false;
end
end
else
valid = false;
end

채택된 답변

Meg Noah
Meg Noah 2021년 12월 28일
Try something like this:
function valid = valid_date(year,month,day)
if ((isscalar(year) && year>0 ) && (isscalar(month) && month>0) && (isscalar(day) && day>0))
%For Leap year
if (((rem(year,4) == 0) && (rem(year,100) == 0) && (rem(year,400) == 0)) || ((rem(year,4) == 0) && (rem(year,100) ~= 0)))
valid_leap = true;
else
valid_leap = false;
end
% check for other months
if ismember(month,[1 3 5 7 8 10 12]) && (day <=31)
valid = true;
elseif ismember(month,[4 6 9 11]) && (day <= 30)
valid = true;
elseif (month == 2 && valid_leap == true && day <=29)
valid = true;
elseif (month == 2 && valid_leap == false && day <=28)
valid = true;
else
valid = false;
end
end
  댓글 수: 1
Sri Thota
Sri Thota 2021년 12월 29일
Hey Meg Noah, Thanks so much for the help : ) It worked.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by