【问题标题】:How to call Array-valued Functions in fortran?如何在 fortran 中调用数组值函数?
【发布时间】:2015-02-27 05:21:03
【问题描述】:

我想写一个在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”,但出现错误:

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

有什么问题?

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

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的功能感到困惑。

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

@Fortranner

【问题讨论】:

  • 对于 1 级数组,Fortran 2003 引入了使用方括号 [] 来分隔数组构造函数。所以,a = (/1,2,3/) 可以写成a = [1, 2, 3]。它更易于阅读。

标签: arrays function fortran


【解决方案1】:

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

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

【讨论】:

  • 谢谢! :),还有一个小问题,我可以使用F18((/1.,2.,3./),3),但是如果我定义了real A(:,:),如何直接传递数组参数呢?
  • 你可以使用内在的reshape:F18( reshape([1,2,3,4], [2,2]) )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
  • 2021-01-19
  • 2011-04-19
相关资源
最近更新 更多