Abe*_*Abe 16 fortran fortran90
我试图读取一些Fortran代码,但无法确定%
(百分号)的作用.
这是一个像:
x = a%rho * g * (-g*a%sigma + m%gb * m%ca * (1.6 * a%rho+g))
Run Code Online (Sandbox Code Playgroud)
它有什么作用?
Nic*_*kLH 29
在Fortran 90中,它们允许您创建类似于C++的结构.它基本上充当点(.)运算符.
来自http://www.lahey.com/lookat90.htm:
结构(派生类型)
您可以使用派生类型对数据进行分组.这使用户能够将内部类型(包括数组和指针)组合成新类型,使用百分号作为分隔符可以访问其中的各个组件.(派生类型在VAX Fortran中称为记录.)!使用派生类型和模块的示例.
module pipedef
type pipe ! Define new type 'pipe', which
real diameter ! is made up of two reals, an
real flowrate ! integer, and a character.
integer length
character(len=10) :: flowtype
end type pipe
end module pipedef
program main
use pipedef ! Associate module pipedef with main.
type(pipe) water1, gas1 ! Declare two variables of type 'pipe'.
water1 = pipe(4.5,44.8,1200,"turbulent") ! Assign value to water1.
gas1%diameter = 14.9 ! Assign value to parts
gas1%flowrate = 91.284 ! of gas1.
gas1%length = 2550
gas1%flowtype = 'laminar'
.
.
.
end program
Run Code Online (Sandbox Code Playgroud)
%
作为代币,它有许多密切相关的用途。随着 Fortran 的发展,这些用途的数量不断增加。
回到 Fortran 90,以及问题中看到的用法,%
用于访问派生类型的组件。a_t
考虑带有a
该类型对象的派生类型:
type a_t
real rho, sigma
end type
type(a_t) a
Run Code Online (Sandbox Code Playgroud)
组件rho
和可以通过和sigma
访问。从问题中可以看出,这些组件可以在表达式中使用(例如),也可以是赋值的左侧()。a
a%rho
a%sigma
a%rho * g
a%rho=1.
派生类型的组件本身可以是派生类型的对象:
type b_t
type(a_t) a
end type
type(b_t) b
Run Code Online (Sandbox Code Playgroud)
因此,%
在单个引用中可能会出现多次:
b%a%rho = ...
Run Code Online (Sandbox Code Playgroud)
rho
这里,派生类型对象 的组件a
(它本身是 的组件b
)是赋值的目标。人们可以在一个引用中看到相当可怕的 s 计数%
,但部分引用总是从左到右解析。
来到 Fortran 2003,人们就会看到%
与派生类型相关的其他几种方式:
考虑派生类型
type a_t(n)
integer, len :: n=1
real x(n)
contains
procedure f
end type
type(a_t(2)) a
Run Code Online (Sandbox Code Playgroud)
该对象a
有一个长度类型参数和一个类型绑定过程。在这样的表达中
x = a%f()
Run Code Online (Sandbox Code Playgroud)
f
派生类型对象的绑定被引用。
n
的参数a
可以被引用为
print *, a%n, SIZE(a%x)
Run Code Online (Sandbox Code Playgroud)
尽可能多地x
引用该组件。
最后,从 Fortran 2008 开始,%
可用于访问复杂对象的实部和虚部:
complex x, y(3)
x%im = 1.
x%re = 0.
y = (2., 1.)
print *, y(2)%im+y(3)%re
Run Code Online (Sandbox Code Playgroud)