函数没有隐式类型

问题描述 投票:10回答:4

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

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
fortran fortran90
4个回答
12
投票

移动线

end program

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

contains

在编写程序时,它不知道test函数,这是编译器告诉你的。我已经提出了一种方法,可以为程序提供所需的知识,但还有其他方法。既然你是一个学习者,我会让你弄清楚究竟发生了什么。


9
投票

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

integer,external :: test

implicit none

在主程序中。


3
投票

把这个:

program main
  implicit none

整数测试

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

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


2
投票

另一个简单的方法,在当前的答案中没有提到:

在主程序之前移动函数,在函数之前放置module subsimplicit 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
© www.soinside.com 2019 - 2024. All rights reserved.