如何在 fortran 中调用数组值函数? [英] How to call Array-valued Functions in fortran?

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

问题描述

我想写一个函数,在 fortran 中返回一个可分配的数组

I want to write a function that returns an allocatable array in fortran

program test
    implicit none
    real a(3)
    real, allocatable :: F18(:)
    a = (/1,2,3/)
    print *, F18(a)
end program test

function F18(A)
implicit none
    real A(:)                   ! An assumed shape array
    real F18(size(A,1))         ! The function result itself is
                               ! the second dimension of A.  
    F18 =A                 !  
end function F18

预计会在屏幕上打印1 2 3",但出现错误:

It is expected to print "1 2 3" on the screen but I got an error:

forrtl:严重 (157):程序异常 - 访问冲突

forrtl: severe (157): Program Exception - access violation

有什么问题吗?

另外,我试过这样的代码:

Also, I have tried code like this:

program test
    implicit none
    real a(3)
    real, allocatable :: F18(:)
    a = (/1,2,3/)
    print *, F18(a,3)
end program test

function F18(A,n)
implicit none
    integer n
    real A(:)                   ! An assumed shape array
    real F18(size(A,1))         ! The function result itself is
                               ! the second dimension of A.  
    F18 =A                 !  
end function F18

在编译过程中我得到:

Intel(R) Visual Fortran Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 14.0.4.237 Build 20140805
Copyright (C) 1985-2014 Intel Corporation.  All rights reserved.

D:\Fortran\Elephant.f90(6): error #6351: The number of subscripts is incorrect.   [F18]
    print *, F18(a,3)
-------------^
compilation aborted for D:\Fortran\Elephant.f90 (code 1)

我真的对 fortran 的功能感到困惑.

I am really confused with fortran's function.

在 fortran 中调用数组值函数的正确方法是什么?

What is the right way to call Array-valued Functions in fortran?

@Fortranner

@Fortranner

推荐答案

你需要让调用者知道函数的属性.最简单的方法是将它放入一个模块并使用"该模块.在您的示例中,您在主程序中声明了一个数组F18",这不是函数.

You need to make the properties of the function known to the caller. The easiest way is to put it into a module and 'use' that module. In your examples, in your main program you are declaring an array 'F18', which is not the function.

module mystuff

contains

function F18(A,n)
implicit none
    integer n
    real A(:)                   ! An assumed shape array
    real F18(size(A,1))         ! The function result itself is
                               ! the second dimension of A.
    F18 =A                 !
end function F18


end module mystuff

program test
    use mystuff
    implicit none
    real a(3)
    a = (/1,2,3/)
    print *, F18(a,3)
end program test

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

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