首页 > 解决方案 > Fortran 类型变量在使用 % 运算符访问时为零

问题描述

我正在尝试使用 % 运算符访问数据类型的元素,但结果为零。我在下面有一些示例代码。

该行print*, t%tsum总是打印出零。但是,当我在子例程中打印 tsum 时,它应该是这样的。

MODULE statistics

PUBLIC :: TimeMarker , start , finish , avgTime , begin , end_ , tsum ,  counts 

TYPE TimeMarker
  REAL*8 :: begin , end_ , tsum 
  INTEGER :: counts = 0
    CONTAINS
            PROCEDURE :: start => start_time
            PROCEDURE :: finish => finish_time
            PROCEDURE :: avgTime => averageTime
END TYPE TimeMarker


CONTAINS


        SUBROUTINE start_time(this)
        CLASS(timeMarker) , INTENT(INOUT) :: this
        CALL CPU_TIME(begin)
            END SUBROUTINE start_time      

            SUBROUTINE finish_time(this)
        CLASS(timeMarker) , INTENT(INOUT) :: this
        CALL CPU_TIME(end_)
        tsum = tsum + end_ - begin
        counts = counts + 1
            END SUBROUTINE finish_time          

            SUBROUTINE averageTime(this)
        CLASS(timeMarker) , INTENT(INOUT) :: this
        WRITE(*,*) "Average time : " , tsum/counts
            END SUBROUTINE averageTime   


END MODULE statistics



program test
  use statistics
  implicit none
  type(TimeMarker) :: t
  integer :: n , m
  real*8 :: a

  do m=1,50    
    call t%start
    do n=1,20000000
      a = sqrt(a)
    end do  

    print*, t%tsum

  end do
  call t%avgTime


end program test

标签: typesfortran

解决方案


在类型绑定过程中,传递对象的组件仍然使用语法来引用argument_name % component_name。传递的对象没有隐含的“this”变量,正如您在其他语言中可能发现的那样。您已将其用作this传递参数的名称 - 例如,必须将 begin 组件引用为this % begin,而不仅仅是begin.

在模块的范围内,隐式类型是有效的——模块没有 IMPLICIT NONE 语句。因此,您在类型绑定过程中操作的变量是隐式声明的模块变量,这意味着编译器不会报告错误。

示例代码中还有其他逻辑错误,需要在修复组件引用后进行处理。

(%不是 Fortran 中的运算符,它只是语法的一部分。)


推荐阅读