[問題] variable 的值已回收

看板MATLAB作者 (bioph)時間16年前 (2009/06/27 03:22), 編輯推噓0(004)
留言4則, 1人參與, 最新討論串1/1
code如下: function res = test_nested_1 a = 1; b = 2; x = 0; y = 9; fprintf('Before call to fun1:\n'); fprintf('a, b, x, y = %2d %2d %2d %2d\n', a, b, x, y); x = fun1(x); fprintf('\nAfter call to fun1:\n'); fprintf('a, b, x, y = %2d %2d %2d %2d\n', a, b, x, y); function res = fun1(y) fprintf('\nAt start of call to fun1:\n'); fprintf('a, b, x, y = %2d %2d %2d %2d\n', a, b, x, y); y = y + 5; a = a + 1; res = y; fprintf('\nAt end of call to fun1:\n'); fprintf('a, b, x, y = %2d %2d %2d %2d\n', a, b, x, y); end end 輸出如下: >> test_nested_1 Before call to fun1: a, b, x, y = 1 2 0 9 At start of call to fun1: a, b, x, y = 1 2 0 0 At end of call to fun1: a, b, x, y = 2 2 0 5 After call to fun1: a, b, x, y = 2 2 5 9 請問為何最後的y是9呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.169.85.44

06/28 15:49, , 1F
在func1內部的y是5, 但你主程式的y是9, 你只有把 內部的y
06/28 15:49, 1F

06/28 15:49, , 2F
傳出來給x,外部的y並沒有改變.
06/28 15:49, 2F

06/28 15:50, , 3F
你顯示的結果第二三行是在內部func理面的結果,非main
06/28 15:50, 3F

06/28 15:50, , 4F
因為是 區域變數
06/28 15:50, 4F
文章代碼(AID): #1AHI0Ja5 (MATLAB)
文章代碼(AID): #1AHI0Ja5 (MATLAB)