在 Fortran 中返回数组的函数 [英] Function Returning an array in Fortran

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

问题描述

据我了解,您可以从 Fortran 中的函数返回一个数组,但由于某种原因,我的代码仅返回我要求它返回的数组中的第一个值.这是功能:

It is my understanding that you can return an array from a function in Fortran, but for some reason my code is only returning the first value in the array I am asking it to return. This is the function:

function polynomialMult(npts,x,y)
    integer npts
    double precision x(npts), results(npts + 1), y(npts,npts)

    polynomialMult =  x(1:npts) + 1

end function

这就是我所说的

 C(1:numPoints) = polynomialMult(numPoints,x,f)

print *, C(1:numPoints)`

现在它没有做任何有用的事情,因为我在编写逻辑之前试图理解语法.我看到了一些关于为函数指定类型的东西,但是当我写

right now it doesn't do anything useful because I am trying to understand the syntax before I write the logic. I saw some stuff about specifying types for functions, but when I write

integer function polynomialMult(npts,x,y)

或者任何我得到的编译错误.

or whatever I get a compilation error.

推荐答案

要定义一个返回数组的函数,包括函数内部的函数声明,像这样:

To define a function which returns an array include the function declaration inside the function, like this:

function polynomialMult(npts,x,y)
    integer npts
    double precision x(npts), results(npts + 1), y(npts,npts)

! Change the next line to whatever you want
    double precision, dimension(npts) :: polynomialMult

    polynomialMult =  x(1:npts) + 1

end function

您的声明

integer function polynomialMult(npts,x,y)

声明函数返回一个整数.一个整数,而不是一个整数数组.我不认为标准允许函数声明,例如:

declares that the function returns an integer. An integer, not an array of integers. I don't think the standard allows function declarations such as:

integer, dimension(10) function polynomialMult(npts,x,y)

但我可能是错的.我总是使用我上面给你展示的表格.

but I could be wrong. I always use the form I showed you above.

如果你有一个最新的 Fortran 编译器,你可以做一些聪明的事情,比如返回一个分配的数组.我建议你弄清楚数组语法.例如,您的声明:

If you have an up to date Fortran compiler you can do clever things such as return an allocated array. And I suggest you figure out array syntax. For example, your statement:

polynomialMult =  x(1:npts) + 1

可以更简洁地写成:

polynomialMult =  x + 1

因为 Fortran 会将标量加法映射到数组 x 的所有元素,这些元素已声明为只有 npts 元素.

since Fortran will map the scalar addition to all elements of the array x which you have declared to have only npts elements.

将数组的大小传递给子例程是非常 FORTRAN77 的,现在几乎总是不必要的.通常,您要么希望对数组中的每个元素进行操作(如数组语法示例中所示),要么应该让子程序计算出它正在处理的数组的大小.

Passing the sizes of arrays into subroutines is very FORTRAN77 and almost always unnecessary now. Generally you either want to operate on every element in an array (as in the array syntax example) or you should let the subprogram figure out the size of the array it is dealing with.

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

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