Need help on this program
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dates and Time 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!