How can i change my code by using the mod command?

Any advice or help would be greatly appreciated.
%program dayofweek.m This program acceptes any day from this month
%(April 2017) and returns the day of the week.
N=input('Enter a date for April 2017 to display the day of the week. ')
if N==0
disp('Enter a day that does not equal zero. ')
elseif N==2
disp('Sunday')
elseif N==9
disp('Sunday')
elseif N==16
disp('Sunday')
elseif N==23
disp('Sunday')
elseif N==30
disp('Sunday')
elseif N==3
disp('Monday')
elseif N==10
disp('Monday')
elseif N==17
disp('Monday')
elseif N==24
disp('Monday')
elseif N==4
disp('Tuesday')
elseif N==11
disp('Tuesday')
elseif N==18
disp('Tuesday')
elseif N==25
disp('Tuesday')
elseif N==5
disp('Wednesday')
elseif N==12
disp('Wednesday')
elseif N==19
disp('Wednesday')
elseif N==26
disp('Wednesday')
elseif N==6
disp('Thursday')
elseif N==13
disp('Thursday')
elseif N==20
disp('Thursday')
elseif N==27
disp('Thursday')
elseif N==7
disp('Friday')
elseif N==14
disp('Friday')
elseif N==21
disp('Friday')
elseif N==28
disp('Friday')
elseif N==1
disp('Saturday')
elseif N==8
disp('Saturday')
elseif N==15
disp('Saturday')
elseif N==22
disp('Saturday')
elseif N==29
disp('Saturday')
elseif N>30
disp('The entered date does NOT exist. Please enter another date. ')
end

回答 (3 件)

dpb
dpb 2017 年 4 月 7 日
編集済み: dpb 2017 年 4 月 8 日

1 投票

After your error checking all you need is
...
days={'Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday'};
disp(days{mod(N,7}+1)
This is, of course, only valid for a month that begins on a Saturday; it would be more useful to use a more general routine.
NB: Unless this is homework, look at
doc weekday % more general routine
Sure there are some other newer routines with the datetime class now, too, but haven't looked for just what might be the best in that vein...
John D'Errico
John D'Errico 2017 年 4 月 7 日

1 投票

days = {'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'};
days(mod(N,7) + 1)
Shawn Marshall
Shawn Marshall 2017 年 4 月 7 日

0 投票

Thank you dpb and John D'Errico.

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

タグが未入力です。

質問済み:

2017 年 4 月 7 日

編集済み:

dpb
2017 年 4 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by