gpt4 book ai didi

arrays - 如何在 fortran 中调用数组值函数?

转载 作者:行者123 更新时间:2023-12-02 11:02:34 24 4
gpt4 key购买 nike

我想编写一个在 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: severe (157): Program Exception - access violation



有什么问题?

另外,我尝试过这样的代码:
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

最佳答案

您需要让调用者知道函数的属性。最简单的方法是将其放入模块中并“使用”该模块。在您的示例中,在您的主程序中,您声明了一个数组'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

关于arrays - 如何在 fortran 中调用数组值函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33019091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com