1、Chapter 7 Subroutine and Function,7-1 subroution(副程式),7-1 subroution(副程式),7-1 subroution(副程式),主副程式變數的宣告 副程式獨立地擁有屬於自己 的變數宣告,若主程式與副 程式用了同樣的變數名稱, 那它們仍然互不相關的,彼 此之間不會有任何的關係。,7-1 subroution(副程式),7-1 subroution(副程式),副程式內參數的宣告 real, intent(in) : A,7-1 subroution(副程式),副程式內參數的宣告,7-1 subroution(副程式),副程式內參數的宣告,
2、7-1 subroution(副程式),副程式內參數的宣告,7-1 subroution(副程式),參數的傳遞 pass-by-reference Fortran在傳遞參數時, 是傳遞這個變數的記憶體位址,7-1 subroution(副程式),參數的傳遞 傳遞參數要注意參數的資料型態和順序real : a, b(4) real, intent(out) : xreal, dimension(4), intent(in) : y integer : next integer : Icall sub1(a, b, next)subroutine sub1(x, y, i),7-1 subrout
3、ion(副程式),參數的傳遞,7-1 subroution(副程式),陣列參數的傳遞 利用傳遞參數的方式傳遞陣列大小,7-1 subroution(副程式),陣列參數的傳遞 利用*作為假定的陣列大小宣告陣列,7-2 save,程式說明 integer, save : n,7-2 save,7-2 save,7-3 利用module共用資料,共用自訂資料型態,7-3 利用module共用資料,全域變數,7-3 利用module共用資料,共用常數,7-4 Fortran Functions,程式內定函數 內建在Fortran語言,可以直接使用,Ex. sin(x) 或 log(x),7-4 For
4、tran Functions,自定函數,7-4 Fortran Functions,函數的宣告function fun_1 (argument_list)integer : fun_1integer function fun_1(argument_list),7-4 Fortran Functions,7-4 Fortran Functions,7-5 利用參數的方式傳遞自訂函數,7-6 Interface(介面),程式說明 interface. end interface,7-6 Interface(介面),7-6 Interface(介面),7-6 Interface(介面),7-6 In
5、terface(介面),7-6 Interface(介面),7-6 Interface(介面),Fortran 90 的標準並沒有嚴格限制一定要寫作 interface,但是在下面的情況之下,寫作 interface是必要的:指定參數位置來傳遞參數時 所呼叫的函式參數數目不固定時 傳入指標參數時 陣列參數沒有設定大小時 函數傳回值為陣列時 函數傳回值為指標時,7-7 不定個數的參數傳遞,程式說明 integer, intent(in), optional : bpresent(b),7-7 不定個數的參數傳遞,7-7 不定個數的參數傳遞,7-8 Recursive(遞迴)procedures,
6、程式說明 recursive subroutine fact(n, ans)call fact(n-1, temp),7-8 Recursive(遞迴)procedures,遞迴說明 Ex.算n階層,7-8 Recursive(遞迴)procedures,7-8 Recursive(遞迴)procedures,7-8 Recursive(遞迴)procedures,7-8 Recursive(遞迴)procedures,7-8 Recursive(遞迴)procedures,7-8 Recursive(遞迴)procedures,7-9 Contains statement,定義某些函數或副程
7、式只能被某個特定的函數(或 副程式)、或是只能在主程式中被呼叫 program scoping_testcall sub2containssubroutine sub2end subroutine sub2 end program scoping_test,7-9 Contains statement,7-9 Contains statement,7-9 Contains statement,7-9 Contains statement,7-9 Contains statement,Beginning: 1 2 100.0 200.0In sub1 before sub2 : 1 2In su
8、b1 in sub3 : 1000 2000In sub1 after sub2 : 1 2000 After array def in sub2 : 1 2000 TEST ? 2000 3000? 5000After sub1: 1 2000 100.0 200.0In sub2: 1000.0 2000.0After sub2: 1 2000 100.0 2000.0,7-9 Contains statement,模組中可以容納其他模組、副程式與函數的存在,7-9 Contains statement,7-9 Contains statement,7-9 Contains statement,7-10 Intrinsic & External,在實際寫作程式時,intrinsic與external可以省 略,不過當我們要把函式名稱當成參數來傳遞到 其它函式中時,external及intrinsic就不能省略 integer, external : Func1, Func2real, intrinsic : sin, cos,7-10 Intrinsic & External,