【发布时间】:2011-12-27 08:37:56
【问题描述】:
我正在尝试阅读一些 Fortran 代码,但无法确定 %(百分号)的作用。
它在一行中:
x = a%rho * g * (-g*a%sigma + m%gb * m%ca * (1.6 * a%rho+g))
它有什么作用?
【问题讨论】:
我正在尝试阅读一些 Fortran 代码,但无法确定 %(百分号)的作用。
它在一行中:
x = a%rho * g * (-g*a%sigma + m%gb * m%ca * (1.6 * a%rho+g))
它有什么作用?
【问题讨论】:
% 作为令牌有许多密切相关的用途。随着 Fortran 的发展,这些用途越来越多。
回到 Fortran 90 和问题中看到的用法,% 用于访问派生类型的组件。考虑派生类型a_t 和该类型的对象a:
type a_t
real rho, sigma
end type
type(a_t) a
a 的组件rho 和sigma 可以通过a%rho 和a%sigma 访问。从问题中可以看出,这些组件可能用在表达式中(例如a%rho * g),也可能是赋值的左侧(a%rho=1.)。
派生类型的组件本身可能是派生类型的对象:
type b_t
type(a_t) a
end type
type(b_t) b
因此% 可能会在一个引用中出现多次:
b%a%rho = ...
这里,派生类型对象a的组件rho本身就是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
对象a 有一个长度类型参数和一个类型绑定过程。像
x = a%f()
引用了派生类型对象的绑定f。
a的参数n可以引用为
print *, a%n, SIZE(a%x)
可能会引用组件x。
最后,从 Fortran 2008 开始,% 可用于访问复杂对象的实部和虚部:
complex x, y(3)
x%im = 1.
x%re = 0.
y = (2., 1.)
print *, y(2)%im+y(3)%re
【讨论】:
在 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
【讨论】:
gas1 修改一个变量,而无需使用整个构造函数 ie 而无需使用所有需要的变量(water1 = pipe(4.5,44.8,1200,"turbulent"))。
它是派生类型的部件标识符。看一下这个。 http://www.lahey.com/lookat90.htm
【讨论】: