Can anyone point out the mistake in this program? It's regarding writing a function to check if the entered date is valid or not.
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Here is the code that I have written, but it gives wrong answers for date such as 31st April 2018 (2018,4,31). Ideally the program should give me logical 0, however, it gives me logic 1.
function [valid]=valid_date(year, month, day)
if isscalar(year) && year>0 && year~=0 && isscalar(month) && month>0 && month~=0 && isscalar(day) && day>0 && ar
if mod(year,4) == 0 && mod(year, 100)~= 0 || mod(year,400)==0 && month==2 && days<=29
%for february
valid=true;
else
valid=false;
end
%for rest of the months
if month==4 || month==6 || month==9 || month==11 && day<=30
valid=true;
elseif month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month== 12 && day<=31
valid=true;
else
valid=false;
end
%not a leap year
if month==2 && day>28
valid=false;
end
%rest of the months
if month==4 || month==6 || month==9 || month==11 && day<=30
valid=true;
elseif month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month== 12 && day<=31
valid=true;
else
valid=false;
end
else
valid=false;
end
1 Kommentar
Antworten (1)
praveen
am 19 Feb. 2019
it has to be
if (month==4 || month==6 || month==9 || month==11) && day<=30
valid=true;
elseif (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month== 12) && day<=31
valid=true;
else
valid=false;
end
Use Parentheses generously. It is a good idea to use parentheses to explicitly specify the intended precedence of statements containing combinations of & and |
1 Kommentar
Siehe auch
Kategorien
Mehr zu Dynamic System Models finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!