If else condition to determine if a year is a leap year

48 ビュー (過去 30 日間)
chafah zachary
chafah zachary 2014 年 3 月 7 日
コメント済み: Rik 2020 年 3 月 31 日
Hi there. Given a variable Y which stores a year in the 20th century (between 1901 and 2000), write MATLAB code to create a variable Days and assign it a value of 366 if the year is a leap year or a value of 365 otherwise.
  1 件のコメント
Jos (10584)
Jos (10584) 2014 年 3 月 7 日
Homework, not? What did you try yourself?

サインインしてコメントする。

採用された回答

Jos (10584)
Jos (10584) 2014 年 3 月 7 日
function Days = GetDays (Y)
if isLeapYear(Y)
Days = 365 ;
else
Days = 366 ;
end
Now your problem is to write second function IsLeapYear that returns true for leap years. (hint: see Nitin's answer)

その他の回答 (3 件)

Nitin
Nitin 2014 年 3 月 7 日
These are the conditions for a leap year :
  • The year is evenly divisible by 4;
  • If the year can be evenly divided by 100, it is NOT a leap year, unless;
  • The year is also evenly divisible by 400. Then it is a leap year.
I have done the first part, I'll leave the rest to you to implement
if mod(year,4)== 0 % use the modulo operator to check for remainder
days == 366
else
days == 365
end

Ian
Ian 2016 年 9 月 8 日
ndays = datenum(Y+1,0,0) - datenum(Y,0,0);
isleap = ndays == 366;

Shikhar Srivastava
Shikhar Srivastava 2020 年 3 月 28 日
編集済み: Shikhar Srivastava 2020 年 3 月 28 日
if(year/4==0 || year/400==0 && ~((year/100==0)))
  4 件のコメント
Rik
Rik 2020 年 3 月 31 日
Complete code posted as answer in another thread:
%sir, i wrote this code,but it is passing nly random leap yeara,can u point out the mistake.%
function valid=valid_date(year,month,day)
if(year/4==0 || (year/400==0 && ~((year/100==0))))
if(3<=month && month<13 || month==1 && 1<=day && day<32)
valid=true;
elseif(month==2 && 1<=day && day<30)
valid=true;
else
valid=false;
end
else
if(3<=month && month<13 || month==1 && 1<=day && day<32)
valid=true;
elseif (month==2 && 1<=day && day<29)
valid=true;
else
valid=false;
end
end
Rik
Rik 2020 年 3 月 31 日
You are using division. Consider the year 2004, which was a leap year. What happens for each of your checks?
year/4==0% year/4 is 501, so this returns false
year/400==0% year/400 is 5.01, so this returns false
~(year/100==0)% year/100 is 20.04, so this returns true
%so your if is this:
if false || (false && true)
If you describe it with words, what is the condition to check if a year is a leap year?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by