types - 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
解决方案
在类型绑定过程中,传递对象的组件仍然使用语法来引用argument_name % component_name
。传递的对象没有隐含的“this”变量,正如您在其他语言中可能发现的那样。您已将其用作this
传递参数的名称 - 例如,必须将 begin 组件引用为this % begin
,而不仅仅是begin
.
在模块的范围内,隐式类型是有效的——模块没有 IMPLICIT NONE 语句。因此,您在类型绑定过程中操作的变量是隐式声明的模块变量,这意味着编译器不会报告错误。
示例代码中还有其他逻辑错误,需要在修复组件引用后进行处理。
(%
不是 Fortran 中的运算符,它只是语法的一部分。)
推荐阅读
- android - 保持服务和应用程序代码分开
- powershell - 我可以通过 mstsc 进行 RDP 并在该远程桌面上运行脚本吗?
- android - Android ANR,服务正在锁定主 GUI 活动
- laravel - Laravel 实时使用 socket.io
- node.js - 检查数组,如果每 2 个元素缺少一个值
- bezier - 使用 cytoscape 生成贝塞尔曲线 - 我应该使用哪些参数?
- ruby-on-rails - 使用一台控制器处理数据,无需模型和数据库
- sql - 使用 if else 的 SQL 查询
- java - 对象和基元之间的性能和设计差异
- javascript - 如何在javascript中添加触摸事件(屏幕上的右、左和下)?