Date Validation error in semantics
조회 수: 12 (최근 30일)
이전 댓글 표시
I am not getting the proper result from this code. At the same time haven't been able to find my errors..
function valid=valid_date(year,month,day)
if integer(year,month,day)==2
if leap_year(year)==2
if month>0 && month<12
if month==2
if day>29 || day<1
valid=false;
return
else
valid=true;
return
end
elseif month==1||month==3||month==5||month==7||month==8||...
month==10||month==12
if day>31 || day<1
valid=false;
return
else
valid=true;
return
end
else
if day>30 || day<1
valid=false;
return
else
valid=true;
return
end
end
else
valid=false;
return
end
else
if month>0 && month<12
if month==2
if day>28 || day<1
valid=false;
return
else
valid=true;
return
end
elseif month==1||month==3||month==5||month==7||month==8||...
month==10||month==12
if day>31 || day<1
valid=false;
return
else
valid=true;
return
end
else
if day>30 || day<1
valid=false;
return
else
valid=true;
return
end
end
else
valid=false;
return
end
end
else
valid=false;
return
end
function result1=integer(year,month,day)
if ~isscalar(year) || year<1 || year~=fix(year)||...
~isscalar(month) || month<1 || year~=fix(month)...
~isscalar(day) || day<1 || year~=fix(day)
result1=1;
else
result1=2;
end
function result2=leap_year(year)
if mod(year,400)==0 || (mod(year,4)==0 && mod(year,100)~=0)
result2=1;
else
result2=2;
end
댓글 수: 0
답변 (1개)
Ameer Hamza
2020년 5월 9일
편집: Ameer Hamza
2020년 5월 9일
Why not use built-in MATLAB's function
function isValid = dateVal(year, month, date)
dt = datetime(year, month, date);
[y,m,d] = ymd(dt);
isValid = isequal([y, m, d], [year, month, date]);
end
Example:
K>> dateVal(1900, 2, 29)
ans =
logical
0
K>> dateVal(2000, 2, 29)
ans =
logical
1
댓글 수: 2
Ameer Hamza
2020년 5월 9일
Try to use breakpoint: https://www.mathworks.com/help/matlab/matlab_prog/set-breakpoints.html and run your code line by line. It will help in finding out which conditions are causing problems.
참고 항목
카테고리
Help Center 및 File Exchange에서 Manage Products에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!