功能返回Fortran中的数组 [英] Function Returning an array in Fortran

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

问题描述

这是我的理解是,你可以从Fortran语言函数返回一个数组,但由于某些原因我的code仅返回我要求它返回数组中的第一个值。这是在功能:

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

可以更简明地写成:

could more concisely be written:

polynomialMult =  x + 1

自Fortran语言将映射标量除了你所声明的阵列X的所有元素都只有 NPTS 元素。

传递数组的大小成子程序非常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天全站免登陆