2018.9.19.Matlab實驗四:Matlab程式設計
阿新 • • 發佈:2018-12-11
一、實驗任務和目的
- 熟悉程式設計思想。
- 掌握虛擬碼的編寫方法。
- 掌握分支語句和迴圈結構的用法。
二、實驗內容
- 輸入一個百分制成績,要求輸出成績等級A、B、C、D、E,其中90-100為A,80-89為B,70-79為C,60-69為D,60分以下為E。要求 (1)分別用if語句和switch語句實現; (2)應對輸入的成績進行合理性判斷,對不合理的成績應輸出錯誤資訊。
- 程式設計實現一個九九乘法表,並螢幕顯示出來,如下圖所示:
- 計算the day of year(年積日),the day of year 是指這一年已經逝去的天數(包括當天)。在平年中,它的取值範圍為1到365,在閏年中,它的取值範圍1 到366。編寫一個MATLAB 程式,輸入年、月、日,輸出為對應的the of year。
三、實驗過程和結果
- 輸入一個百分制成績,要求輸出成績等級A、B、C、D、E,其中90-100為A,80-89為B,70-79為C,60-69為D,60分以下為E。要求 (1)分別用if語句和switch語句實現; If語句:
x=input(‘成績’); if x>=90&&x<=100 disp('A'); elseif x>=80&&x<=89 disp('B'); elseif x>=70&&x<=79 disp('C'); elseif x>=60&&x<=69 disp('D'); else disp('E'); end
switch語句:
x=input('成績');
switch x
case num2cell(90:100)
disp('A');
case num2cell(80:89)
disp('B');
case num2cell(70:79)
disp('C');
case num2cell(60:69)
disp('D');
otherwise
disp('E');
end
(2)應對輸入的成績進行合理性判斷,對不合理的成績應輸出錯誤資訊。
x=input('成績'); if(x>100||x<0) disp('wrong input'); else switch x case num2cell(90:100) disp('A'); case num2cell(80:89) disp('B'); case num2cell(70:79) disp('C'); case num2cell(60:69) disp('D'); otherwise disp('E'); end end
- 程式設計實現一個九九乘法表,並螢幕顯示出來,如下圖所示:
for i=1:9
for j=1:i
fprintf('%dx%d=%d',j,i,i*j);
if(j~=i)
fprintf(' ');
end
end
fprintf('\n');
end
- 計算the day of year(年積日),the day of year 是指這一年已經逝去的天數(包括當天)。在平年中,它的取值範圍為1到365,在閏年中,它的取值範圍1 到366。編寫一個MATLAB 程式,輸入年、月、日,輸出為對應的the of year。
y=input('年');
m=input('月');
d=input('日');
sum=0;
a=[31,28,31,30,31,30,31,31,30,31,30,31];
b=[31,29,31,30,31,30,31,31,30,31,30,31];
if(y<0||m<0||d<0||m>12||d>31)
fprintf('wrong input');
else
if(mod(y,400)==0||mod(y,100)~=0 && mod(y,4)==0)
for i=1:m-1
sum=sum+b(i);
end
if(d>b(m)) fprintf('wrong input');
else fprintf('%d',sum+d);
end
else
for i=1:m-1
sum=sum+a(i);
end
if(d>b(m)) fprintf('wrong input');
else fprintf('%d',sum+d);
end
end
end
四、實驗總結和心得
熟悉了程式設計思想。 掌握了虛擬碼的編寫方法。 掌握了分支語句和迴圈結構的用法。