[討論] 關於structure

看板MATLAB作者 (toytoy)時間14年前 (2011/12/13 10:56), 編輯推噓0(006)
留言6則, 2人參與, 最新討論串1/1
最近在練習structure指令 但是卻出現一點小問題 想請問高手 我的程式碼是這樣的 function out = exlevel(in) if in < 60 out='不及格'; elseif in < 70 out='D'; elseif in < 80 out='C'; elseif in < 90 out='B'; elseif in < 100 out='A'; else in == 100 out='S'; end ------------------------------------------------ keyb='y'; k=1; while keyb=='y' st(k).id=input('請輸入學生學號 = ','s'); st(k).name=input('請輸入學生姓名 = ','s'); st(k).score(1)=input('請輸入第一次成績 = '); st(k).score(2)=input('請輸入第二次成績 = '); st(k).score(3)=input('請輸入第三次成績 = '); avescore =floor((st(k).score(1)+st(k).score(2)+st(k).score(3))/3); level = exlevel(avescore); st(k).avescore=avescore; st(k).level=level; k=k+1; keyb = input('繼續輸入資料? 請按 y ','s'); end fprintf('\n==學號====姓名==第1次成績==第2次成績==第3次成績=學期平均==評等 ==\n'); for i=1:k fprintf('%s %s%8d%10d%10d%10d %s\n',st(i).id,st(i).name,st(i).score(1),st(i).score(2),st(i).score(3),st(i).avescore,st(i).level) end 前面都可以執行 但是最後會出現這一段錯誤 ??? Index exceeds matrix dimensions. Error in ==> structure at 20 fprintf('%s%s%8d%10d%10d%10d%s\n',st(i).id,st(i).name,st(i).score(1),st(i).score(2),st(i).score(3),st(i).avescore,st(i).level) 請問我該如何修改呢?? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 210.240.188.150

12/13 11:20, , 1F
你的資料存到k 但在迴圈最後多跑了一次k=k+1
12/13 11:20, 1F

12/13 11:21, , 2F
for的最後一次會讀不到東西
12/13 11:21, 2F

12/13 11:24, , 3F
那我該如何修改?
12/13 11:24, 3F

12/13 11:26, , 4F
i=1:k-1 這樣嗎
12/13 11:26, 4F

12/13 11:32, , 5F
應該可以
12/13 11:32, 5F

12/13 17:18, , 6F
我改成i=1:k-1就成功了 感謝D大
12/13 17:18, 6F
文章代碼(AID): #1EvhxJbM (MATLAB)