필터 지우기
필터 지우기

my code works for some inputs, but not others

조회 수: 2 (최근 30일)
Alexandra Huff
Alexandra Huff 2016년 8월 8일
답변: Walter Roberson 2016년 8월 8일
Hi. My function returns a positive integer scalar that is equal to the difference between the ages of the two children in days. However, my code is working for some inputs but not others.
function dd = day_diff(month1, day1, month2, day2)
if (month1 && month2 > 0) || (month1 && month2 <= 12)
if month1 == 1 && month2 == 1
if day1 == day2
total1 = day1;
total2 = day2;
elseif day1 ~= day2
total1 = max(day1,day2);
total2 = min(day1,day2);
end
elseif month1 == 1 && month2 == 2
total1 = day1;
total2 = day2 + 31;
elseif (month1 == 2 && day1 <= 28) && month2 == 1
total1 = day1 + 31;
total2 = day2;
elseif month1 == 1 && month2 == 12
total1 = day1;
total2 = day2 + 334;
elseif month1 == 2 && month2 == 3
total1 = day1 + 31;
total2 = day2 + 59;
elseif month1 == 7 && month2 == 9
total1 = day1 + 181;
total2 = day2 + 243;
else
dd = -1;
return
end
end
dd = (max(total1,total2)) - (min(total1,total2));
So I started to test some numbers and it worked for lets say (2, 29,1, 22) for (month1, day 1, month2, day2).When i tested for (1,13,4,30) it did not work.

답변 (1개)

Walter Roberson
Walter Roberson 2016년 8월 8일
The expression
month1 && month2 > 0
Does not mean to test that month1 and month2 are both greater than 0. Instead, it means
(month1 ~= 0) && (month2 > 0)
Likewise
(month1 && month2 <= 12)
means
((month1 ~= 0) && (month2 <= 12))

카테고리

Help CenterFile Exchange에서 App Building에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by