Defining a function returning an array

后端 未结 2 984
梦毁少年i
梦毁少年i 2020-12-01 22:12

I have the following code:

    Program function_as_an_array
    implicit none
    integer:: i
    integer, parameter:: N=10
    real*8:: x(N),y(N),f(N)

            


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 22:35

    This is working for me:

    Program function_as_an_array
    implicit none
    integer:: i
    integer, parameter:: N=10
    real*8 :: x(N),y(N),f(N)
    interface func
      function func(x,N) result(f)
        implicit none
        integer N
        real*8:: x(N),f(N) 
      end function
    end interface
    
    do i=1,N
      x(i)=float(i)
    end do
    
    f = func(x,N)
    
    open(unit=20, file='test.dat')
    do i=1,N
      y(i)=f(i)
      write(20,*) x(i),y(i) 
    end do
    close(20)
    Stop 
    End Program function_as_an_array
    
    
    function func(x,N) result(f)
    implicit none
    integer i, N
    real*8:: x(N),f(N) 
    
    do i=1,N
       f(i)=x(i)**2
    end do
    
    end function
    

    You need to:

    • use result for an array-valued return variable [edit] or specify func as real*8:: func(N). See the comments for details.
    • use an explicit interface for external functions (or a module which has an implicit interface, see Jonathan Dursi's answer )

    Then, you can directly assign the return value of the function to the array.

提交回复
热议问题