doy.asv

来自「学习Matlab循环语句的好例子」· ASV 代码 · 共 65 行

ASV
65
字号
%Script file:doy.m
%
%Purpose:
%   This program calculates the day of year corresponding
%   to a specified date.It illustrates the use switch and 
%    for constructs
%
% Record of revision:
%    Date     Programmer            Description of change
%   =====    ============         =========================
%   12/07/98  S.J.Chapman         Original code
%   06/06/08   ZMW                modified data validation
%
% Define variables
%day    ----------Day(dd)
%day_of_year ----Day of year
%ii          ---- Loop index
%month     ------Month(mm)
%year          -----Year(yyyy)

%Get day,month,and year to convert

disp('This program calculates the day of year given the ');
disp('Current date.');
month=input('Enter current month(1-12):');
while month>12 | month<1
    disp('Please input validate month')
    month=input('Enter current month(1-12):');
end

day=input('Enter current day(1-31):');
while day>31 | day<1
    if month==2 & day>29
    disp('Please input validate day');
    day=input('Enter current day(1-31):');
    
end
year=input('Enter current year(yyyy):');

%Check for leap year,and add extra day if necessary
if mod(year,400)==0
    leap_day=1;
elseif mod(year,100)==0
    leap_day=0;
elseif mod(year,4)==0
    leap_day=1;
else
    leap_day=0;
end

%Calculate day of year by adding current day to the days in previous months
day_of_year=day;
for ii=1:month-1
    % Add days in months from January to last month
    switch(ii)
        case {1,3,5,7,8,10,12},
            day_of_year=day_of_year+31;
        case {4,6,9,11},
            day_of_year=day_of_year+30;
        case 2,
            day_of_year=day_of_year+28+leap_day;
    end
end 
%Tell user
fprintf('The date %2d/%2d/%4d is day of year %d.\n',month,day,year,day_of_year);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?