如何在Fortran中创建函数? [英] How to create functions in Fortran?

查看:118
本文介绍了如何在Fortran中创建函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定解决方案是非常基本的,但是我很难弄清楚如何在Fortran中使用函数.我有以下简单程序:

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

我已经尝试了几种变体,包括在FUNCTION之前分配数据类型,将funct的结果分配给主程序中的另一个变量并打印该变量,以及将FUNCTION块移至PROGRAM块上方.这些都不起作用.使用当前程序,我在第6行(带有PRINT语句的行)出现错误:

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?

推荐答案

仅将函数放入文件中将不会使主程序可以访问该函数.

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

传统上,您可以简单地将函数声明为external,而编译器只是希望在编译时找到合适的声明.

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

现代Fortran在模块"中组织代码和数据.但是,出于您的目的,将功能包含"在主程序范围内较为简单,如下所示:

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

这篇关于如何在Fortran中创建函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆