How to create functions in Fortran?

心已入冬 提交于 2019-12-02 13:53:10

问题


I'm sure the solution to this is extremely basic, but I'm having a hard time figuring out how to use functions in Fortran. I have the following simple program:

  PROGRAM main
    IMPLICIT NONE
    INTEGER :: a,b
    a = 3
    b = 5
    PRINT *,funct(a,b)
  END PROGRAM

  FUNCTION funct(a,b)
    IMPLICIT NONE
    INTEGER :: funct
    INTEGER :: a,b

    funct = a + b
  END FUNCTION

I've tried several variations of this, including assigning a data type before FUNCTION, assigning the result of funct to another variable in the main program and printing that variable, and moving the FUNCTION block above the PROGRAM block. None of these worked. With the current program I get an error on line 6 (the line with the PRINT statement):

Error: Return type mismatch of function 'funct' (UNKNOWN/INTEGER(4))
Error: Function 'funct' has no IMPLICIT type

From all of the guides I've tried, I seem to be doing it right; at least one of the variations, or a combination of some of them, should have worked. How do I need to change this code to use the function?


回答1:


Simply putting the function in the file will not make it accessible to the main program.

Traditionally, you could simply declare a function as external and the compiler would simply expect to find a suitable declaration at compile-time.

Modern Fortran organizes code and data in "modules". For your purpose, however, it is simpler to "contain" the function within the scope of the main program as follows:

PROGRAM main
  IMPLICIT NONE
  INTEGER :: a,b
  a = 3
  b = 5
  PRINT *,funct(a,b)

CONTAINS

  FUNCTION funct(a,b)
    IMPLICIT NONE
    INTEGER :: funct
    INTEGER :: a,b

    funct = a + b
  END FUNCTION funct
END PROGRAM main


来源:https://stackoverflow.com/questions/45932426/how-to-create-functions-in-fortran

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!