필터 지우기
필터 지우기

I want an if-else statement to check whether the a part of the input is a decimal or not? The following program gave an error for input (2.3, 4, 5, 6)

조회 수: 3 (최근 30일)
function dd = day_diff(m1, d1, m2, d2)
m(1:12) = [31 28 31 30 31 30 31 31 30 31 30 31];
if m1>=13 && m2>=13 && d1>=32 && d2>=32
dd=-1;
elseif (m1==2 && d1>=29) || (m2==2 && d2>=29)
dd=-1;
elseif (m1==4 && d1>=31) || (m1==6 && d1>=31) || (m1==9 && d1>=31) || (m1==11 && d1>=31)
dd=-1;
elseif (m1==1 && d1>=32) || (m1==3 && d1>=32) || (m1==5 && d1>=32) || (m1==7 && d1>=32) || (m1==8 && d1>=32) || (m1==10 && d1>=32) || (m1==12 && d1>=32)
dd=-1;
elseif (m2==4 && d2>=31) || (m2==6 && d2>=31) || (m2==9 && d2>=31) || (m2==11 && d2>=31)
dd=-1;
elseif (m2==1 && d2>=32) || (m2==3 && d2>=32) || (m2==5 && d2>=32) || (m2==7 && d2>=32) || (m2==8 && d2>=32) || (m2==10 && d2>=32) || (m2==12 && d2>=32)
dd=-1;
elseif (m1<=0 || d1<=0) || (m2<=0 || d2<=0)
dd=-1;
elseif m1<=12 && m2<=12 && d1<=31 && d2<=31
dd=abs(sum(m(m1:m2)) - d1 - (m(m2)-d2));
end
end

답변 (1개)

per isakson
per isakson 2018년 12월 14일
편집: per isakson 2018년 12월 14일
I get a warning (not an error) and that's because 2.3 isn't an integer.
>> day_diff( 2.3, 4, 5, 6 );
Warning: Integer operands are required for colon operator when used as index.
> In day_diff (line 19)
where line 19 is
dd=abs(sum(m(m1:m2)) - d1 - (m(m2)-d2));
Add
inarg = [m1,d1,m2,d2];
if all(inarg==round(inarg))
disp('all input arguments are whole numbers')
else
disp('one or more of the input arguments are NOT whole numbers')
dd = [];
return
end
in the beginning of the function.
  댓글 수: 2
Ashwin Raju
Ashwin Raju 2018년 12월 14일
Thank you for the solution but I want the output as -1 when any input is decimal.
per isakson
per isakson 2018년 12월 14일
편집: per isakson 2018년 12월 14일
Thus replace
dd = [];
by
dd = -1;
and delete the disp-statements if you don't want the text output in the command window

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품


릴리스

R2015b

Community Treasure Hunt

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

Start Hunting!

Translated by