我正在學習用 fortran 編程,并且正在制作一個基本程式。在其中我試圖從我的程式中的函式回傳一個陣列,這導致了這個錯誤:Interface mismatch in global procedure 'test1' at (1): Rank mismatch in function result (0/1).
下面是錯誤的重建:
program Test
implicit none
integer :: a
interface
function test1(n) result (m)
integer :: n
end function test1
end interface
a = test1(4)
end program Test
function test1(n) result (m)
implicit none
integer :: n, m(2)
m(1) = n**2
end function test1
錯誤是在interface陳述句之??后function test1(n) result (m)。
由于我是 fortran 的新手,我認為我錯過了一些基本的東西,因此感謝您的幫助。
uj5u.com熱心網友回復:
的介面和實作的test1引數不匹配,并且a與 的結果不匹配test1。如果您宣告a為一個長度陣列,并向您2添加一個宣告,也就是一個長度陣列,那么一切都應該作業:minterface2
program Test
implicit none
integer :: a(2)
interface
function test1(n) result (m)
integer :: n, m(2)
end function test1
end interface
a = test1(4)
write(*,*) a
end program Test
function test1(n) result (m)
implicit none
integer :: n, m(2)
m(1) = n**2
end function test1
宣告函式
在全域范圍內宣告函式并通過 an 呼叫它們interface會導致大量多余的代碼撰寫和維護。有兩種更好的方法來宣告函式;作為內部函式,或在模塊中。
如果你正在撰寫一個簡短的程式,你可以將你的函式直接放在你的程式中,使用contains. 這完全擺脫了對介面的需求:
program Test
implicit none
integer :: a(2)
a = test1(4)
contains
function test1(n) result (m)
integer :: n, m(2)
m(1) = n**2
end function test1
end program Test
請注意,我已經implicit none從函式中洗掉了,因為它現在繼承自Test.
如果您的代碼變得有點大,您將需要在單獨的模塊中宣告您的函式,如下所示:
module test_module
implicit none
contains
function test1(n) result (m)
integer :: n, m(2)
m(1) = n**2
end function test1
end module
program Test
use test_module
implicit none
integer :: a(2)
a = test1(4)
end program Test
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/438313.html
上一篇:將所選術語的ID回傳到陣列
