Need help on this program

1 visualización (últimos 30 días)
Sri Thota
Sri Thota el 28 de Dic. de 2021
Comentada: Sri Thota el 29 de Dic. de 2021
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

Respuesta aceptada

Meg Noah
Meg Noah el 28 de Dic. de 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
  1 comentario
Sri Thota
Sri Thota el 29 de Dic. de 2021
Hey Meg Noah, Thanks so much for the help : ) It worked.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Dates and Time en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by