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 Center および File ExchangePolar Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by