Date Validation error in semantics

1 回表示 (過去 30 日間)
Anowarul Faruk  Shishir
Anowarul Faruk Shishir 2020 年 5 月 9 日
コメント済み: Ameer Hamza 2020 年 5 月 9 日
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

回答 (1 件)

Ameer Hamza
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 件のコメント
Anowarul Faruk  Shishir
Anowarul Faruk Shishir 2020 年 5 月 9 日
編集済み: Anowarul Faruk Shishir 2020 年 5 月 9 日
It was a task where using built in function was prohibited
Ameer Hamza
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 ExchangeManage Products についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by