14

我正在尝试学习使用函数。我有以下代码:

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

当我编译(使用 gfortran 4.1.2)时,出现以下错误:

In file test.f90:4

  write(*,*) test(4)
           1
Error: Function 'test' at (1) has no IMPLICIT type
4

4 回答 4

19

移动线

end program

到源文件的末尾,并在其位置写入该行

contains

当您编写程序时,它对函数一无所知test,这是编译器告诉您的。我已经提出了一种可以为程序提供所需知识的方法,但还有其他方法。由于您是学习者,因此我将让您详细了解发生了什么。

于 2013-07-19T17:54:16.623 回答
10

以防万一,有人有同样的问题另一种方法(特别是对于评论中讨论的情况)是添加

integer,external :: test

implicit none

在主程序中。

于 2014-03-28T13:05:01.280 回答
5

另一种简单的方法,当前答案中未提及:

将函数移到主程序之前、放置module subs、函数之前implicit nonecontains函数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
于 2019-03-19T14:44:37.760 回答
3

放这个:

program main
  implicit none

整数检验

  write(*,*) test(4)
end program
...

您需要将函数声明为变量,以便编译器知道函数的返回类型。

于 2015-05-07T03:33:41.897 回答