How to write a function to determine if the inputed date is valid.Whats wrong with my valid_date function?

3 visualizaciones (últimos 30 días)
function valid = valid_date(year,month,day)
if isscalar(year)==true && year>0 && isscalar(month)==true && month>0 && 12>=month && isscalar(day)==true && day>0 %checks if input is correct
if (mod(year,4) == 0 && mod(year, 100)~= 0 || mod(year,400)==0) %checks if it's leap
isleap=true;
else
isleap=false;
end
if( any(month == [4,6,9,11]) && day<=30 )
valid = true;
if ( any(month == [1,3,5,7,8,10,12]) && day<=31)
valid = true;
else
valid=false;
end
end
elseif isleap == true && month == 2 && day<=29 || isleap == false && month ==2 && day<=28
valid=true;
else
valid=false;
end
else
valid=false;
end
end

Respuestas (1)

James Tursa
James Tursa el 11 de Mayo de 2020
Editada: James Tursa el 11 de Mayo de 2020
Consider these lines:
if( any(month == [4,6,9,11]) && day<=30 ) % <-- if you pass this test
valid = true;
if ( any(month == [1,3,5,7,8,10,12]) && day<=31) % <-- then how could you ever pass this test
That is, if the month is one of [4,6,9,11] and you passed that first if-test, then how can you ever pass that 2nd if-test which is inside the if-block of the first test? (You can't)
You need to rethink and rework this logic. Step through it one line at a time to see what it is really doing with those incorrect results.
  4 comentarios
James Tursa
James Tursa el 12 de Mayo de 2020
Editada: James Tursa el 12 de Mayo de 2020
Do you know how to use the debugger? Bring your code up in the editor, then click on a line number, e.g. near the start. When you run your code, it will pause at the line number. Then you can click one of the buttons at the top to step through your code one line at a time. Do this for one of your failed results and then you can see what the code is acutally doing so you can see the flaws in the logic.

Iniciar sesión para comentar.

Categorías

Más información sobre Logical 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