How to write a function to determine if the inputed date is valid.Whats wrong with my valid_date function?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/292287/image.png)
댓글 수: 0
답변 (1개)
James Tursa
2020년 5월 11일
편집: James Tursa
2020년 5월 11일
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
James Tursa
2020년 5월 12일
편집: James Tursa
2020년 5월 12일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!