从外部检查子程序中局部变量的值

时间:2016-02-27 16:31:36

标签: fortran fortran90 gfortran

如何在Matlab中检查Fortran中的值?例如,在小程序中,为什么在子程序c=0c=36时,它显示为testing?你如何在主程序中做到c=36

你能以某种方式调用值c吗?我理解在主程序中变量c未定义或具有值0,但是有一种方法可以在子例程中保存c的值,以便您可以再次使用它在其他子程序中,不再计算它?

当程序非常大时,可以随时查看值。

program main

use test

implicit none

integer :: a,b,c

call testing(a,b)

write(*,*)'Test of c in main program',c


end program main



module test

implicit none


contains


subroutine testing(a,b)

integer :: a,b,c

a=2
b=3

c=(a*b)**a

write(*,*)'Value of c in subroutine',c

end subroutine testing

end module test

2 个答案:

答案 0 :(得分:3)

了解编程语言中的scope非常重要。

每个名称(标识符)的有效范围都有限。

如果在子程序中声明一些变量

subroutine s
  integer :: i
end subroutine

仅比i在该子例程中有效。

如果在模块中声明变量

module m
  integer :: i
contains
  subroutines and functions
end module

然后i在所有子例程和函数中以及use该模块的所有程序单元中都有效。

但是,这并不意味着您应该在模块中声明变量并只是共享它。这或多或少是global variable。这仅适用于某些必要的情况,但不能用于从子程序中获取结果。

如果您的子程序只是计算某些东西,并且您想获得该计算的结果,那么您有两种可能:

1。将其作为附加参数传递,该参数将由子程序

定义
subroutine testing(a, b, c)
    integer, intent(in) :: a, b
    integer, intent(out) :: c

    c = (a*b) ** a
end subroutine

然后将其称为

call testing(2, 3, c)
print *, "result is:" c

2。将其设为功能

function testing(a, b) result(c)
    integer, intent(in) :: a, b
    integer :: c

    c = (a*b) ** a
end function

然后你可以直接使用

c = testing(2, 3)
print *, "result is:", c

或只是

print *, "result is:", testing(2, 3)

答案 1 :(得分:1)

这是所需的行为。基本上调用例程应该对子例程一无所知,除了如何调用它以及返回什么。这称为封装。

您可以通过在模块本身中声明变量来使变量可以访问,而不是在子例程中:

module test
    implicit none
    integer :: c

contains

    subroutine testing(a, b)
        implicit none
        integer :: a, b

        a = 2
        b = 3
        c = (a*b) ** a

        write(*, *) "Value of c in the subroutine: ", c
    end subroutine testing

end module test

program main

    use test
    implicit none
    integer :: a, b

    call testing(a, b)

    write(*, *) "Test of c in the main program: ", c

end program main

请注意,您不能在主程序中声明c,因为它将从模块中获取变量。

您也可以使用COMMON块,但模块更优越。