Need help on this program
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Meg Noah
le 28 Déc 2021
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Dates and Time dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!