sod*_*ate 10 fortran fortran90
我正在努力学习使用函数.我有以下代码:
program main
implicit none
write(*,*) test(4)
end program
integer function test(n)
implicit none
integer, intent(in) :: n
integer :: i, ans
ans=1
do i=1,n
ans=ans*i
enddo
test=ans
end function test
Run Code Online (Sandbox Code Playgroud)
当我编译(使用gfortran 4.1.2)时,我收到以下错误:
In file test.f90:4
write(*,*) test(4)
1
Error: Function 'test' at (1) has no IMPLICIT type
Run Code Online (Sandbox Code Playgroud)
Hig*_*ark 13
移动线
end program
Run Code Online (Sandbox Code Playgroud)
到源文件的末尾,并在其位置写入该行
contains
Run Code Online (Sandbox Code Playgroud)
在编写程序时,它不知道函数test,这是编译器告诉你的.我已经提出了一种方法,可以为程序提供所需的知识,但还有其他方法.既然你是一个学习者,我会让你弄清楚究竟发生了什么.
PeM*_*eMa 10
为了以防万一,有人有相同的问题,另一种方式(特别是对于评论中讨论的情况)是添加
integer,external :: test
Run Code Online (Sandbox Code Playgroud)
后
implicit none
Run Code Online (Sandbox Code Playgroud)
在主程序中.
另一种简单的方法,当前答案中未提及:
将函数移到主程序之前,将module subs、implicit none以及contains函数之前和end module函数之后。放入use subs您的程序中。
这样,程序就可以看到有关模块中过程的所有必要信息(“显式接口”)subs,并知道如何正确调用它们。如果您尝试错误地调用过程,编译器将能够提供警告和错误消息。
module subs
implicit none
contains
integer function test(n)
!implicit none no longer necessary here
end function test
end module
program main
use subs
implicit none
Run Code Online (Sandbox Code Playgroud)