我正在学习fortran并遇到了我正在编写的程序的问题。
该计划如下:
PROGRAM mymain
IMPLICIT NONE
INTEGER :: a, g1
EXTERNAL f
PRINT *, "value of a"
READ *, a
g1 = f(a)
PRINT *, a, g1
END PROGRAM mymain
CONTAINS
INTEGER FUNCTION f(x)
IMPLICIT NONE
INTEGER, INTENT(IN) :: x
f = x*x
RETURN
END FUNCTION f
当我尝试运行程序时,出现以下错误:
xfunc.f90:2.14:
PROGRAM mymain
1
exfunc.f90:17.8:
CONTAINS
2
Error: Two main PROGRAMs at (1) and (2)
我不知道该怎么办。我做错了什么?
答案 0 :(得分:3)
除了使用模块的@ ja72解决方案之外(我也更喜欢),这就是我认为你要做的... CONTAINS
语句定义了内部功能如下。内部函数不能在其范围之外(主程序/子例程/函数)使用,并且可以直接访问该范围内的所有变量。然后您的代码将显示为:
PROGRAM mymain
IMPLICIT NONE
INTEGER :: a, g1
PRINT *, "value of a"
READ *, a
g1 = f(a)
PRINT *, a, g1
CONTAINS ! <-- The CONTAINS statement must come before
! END PROGRAM
INTEGER FUNCTION f(x)
IMPLICIT NONE
INTEGER, INTENT(IN) :: x
f = x*x
RETURN
END FUNCTION f
END PROGRAM mymain
请勿将其与外部功能混合使用,如下所示:
PROGRAM mymain
IMPLICIT NONE
INTEGER :: a, g1
INTEGER :: f ! <-- You need to declare the return value of
! an external function when using IMPLICIT NONE
EXTERNAL f
PRINT *, "value of a"
READ *, a
g1 = f(a)
PRINT *, a, g1
END PROGRAM mymain
INTEGER FUNCTION f(x)
IMPLICIT NONE
INTEGER, INTENT(IN) :: x
f = x*x
RETURN
END FUNCTION f
请注意第一个版本中缺少的EXTERNAL
语句和另一个版本中缺少的CONTAINS
语句。
答案 1 :(得分:0)
试试这个:
MODULE XFUN
CONTAINS
INTEGER FUNCTION f(x)
IMPLICIT NONE
INTEGER, INTENT(IN) :: x
f = x*x
RETURN
END FUNCTION f
END MODULE XFUN
PROGRAM mymain
USE XFUN
IMPLICIT NONE
INTEGER :: a, g1
PRINT *, "value of a"
READ *, a
g1 = f(a)
PRINT *, a, g1
END PROGRAM mymain
它与我合作