How can I compute the leap years?

5 ビュー (過去 30 日間)
Aaron Grubbs
Aaron Grubbs 2017 年 10 月 6 日
編集済み: Walter Roberson 2017 年 10 月 6 日
function leapyr = leapyears(startYear, endYear)
%UNTITLED8 Summary of this function goes here
% Detailed explanation goes here
leapyr = 0;
i = 0;
for i = startYear:4:endYear
if mod(startYear, 4) == 0 && mod(endYear, 4) == 0
fprintf('%i \n', startYear)
elseif mod(startYear, 400) == 0 && mod(endYear, 400) == 0
fprintf('%i \n', startYear)
else mod(startYear, 100) == 0 && mod(endYear, 100) == 0
fprintf('%i \n', startYear)
end
end
end
Hey all, I'm struggling to figure out how I'm supposed to supposed to print a list of leap years given two inputs.
The output is supposed to look like this:
a. Example 1.
>> leapyears(2004,2016)
2004
2008
2012
2016
b. Example 2.
>> leapyears(1881,1907)
1884
1888
1892
1896
1904
Please help and thank you.
  1 件のコメント
KSSV
KSSV 2017 年 10 月 6 日
There is inbuilt command/ function leapyear.

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

回答 (3 件)

Andrei Bobrov
Andrei Bobrov 2017 年 10 月 6 日
Please write script - file now1.m:
out = leapyears(2000,2030)
function out = leapyears(startYear,endYear)
y = (startYear:endYear)';
x = rem(y,[4,100,400]);
out = y(x(:,1)==0 & x(:,2) | x(:,3) == 0);
end
use
>> now1
out =
2000
2004
2008
2012
2016
2020
2024
2028
>>

ES
ES 2017 年 10 月 6 日
編集済み: ES 2017 年 10 月 6 日
function [leapyears] = leapyears(startyear,endyear)
leapyears = [];
for iYr=startyear:endyear
if mod(iYr,4)==0 && (mod(iYr,100)~=0 || mod(iYr,400)==0)
leapyears = [leapyears;iYr];
end
end
end

Mischa Kim
Mischa Kim 2017 年 10 月 6 日
編集済み: Mischa Kim 2017 年 10 月 6 日
Aaron, you could do something like
function leapyr = leapyears(startYear, endYear)
%UNTITLED8 Summary of this function goes here % Detailed explanation goes here
leapyr = [];
for year = startYear:endYear
if mod(year, 4) == 0 % divisible by 4?
if ~(mod(year, 100) == 0 && mod(year, 400) ~= 0)
leapyr = [leapyr,year]; % simply add leap year to vector of leap years
end
end
end
end

カテゴリ

Help Center および File ExchangeSatellite Mission Analysis についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by