fortan中函数形式返回数组

 

001、

fortan中函数值返回数组

root@ubuntu26:/home/test01/fortran02/test# cat test01.f90      ## 测试程序
program test01_fortran
    implicit none

    integer :: i,a
    integer,allocatable :: ay1(:)
    integer,allocatable :: result(:)

    do
        write(*, "(A)", advance="no") "input a: "; read *, a
        if(a >= 1) exit
        print *, "error, a must be >= 1"
    end do
    allocate(ay1(a))
    do i = 1, a
        write(*, "(A,I0,A)", advance="no") "input ay1(", i, "):"; read *, ay1(i)
    end do

    result = array_even(ay1)
    print *, "result even: ", result

    deallocate(ay1)
    deallocate(result)

contains

    function array_even(x) result(y)
        implicit none

        integer,intent(in) :: x(:)
        integer,allocatable :: y(:)
        integer :: i,count

        count = 0
        do i = 1,size(x)
            if(mod(x(i),2) == 0) count = count + 1
        end do

        allocate(y(count))

        count = 0
        do i = 1, size(x)
            if(mod(x(i),2) == 0) then
                count = count + 1; y(count) = x(i)
            end if
        end do
    end function array_even
end program test01_fortran
root@ubuntu26:/home/test01/fortran02/test# gfortran test01.f90 -Wall -O2 -o kkk     ## 编译
root@ubuntu26:/home/test01/fortran02/test# ls
kkk  test01.f90
root@ubuntu26:/home/test01/fortran02/test# ./kkk                                ## 测试
input a: 4
input ay1(1):98
input ay1(2):34
input ay1(3):23
input ay1(4):55
 result even:           98          34

 

image

 。

 

posted @ 2026-11-13 10:39  小鲨鱼2018  阅读(3)  评论(0)    收藏  举报