Fortran中根据字符串动态确定变量名 [英] Determine variable names dynamically according to a string in Fortran
问题描述
我想使用 Fortran 创建一个动态变量名.
I want to create a dynamic variable name using Fortran.
将通过连接一个字符串和另一个字符串/整数来获得变量名.然后我想用这个变量名来存储一个值或另一个变量.
The variable name will be obtained by concatenating a string and another string/integer. Then I want to use this variable name to store a value or another variable.
例如
! assign values to 2 variables
my_string = h
my_integer = 1
! perform concatenation resulting in the dynamic variable name, h1
! Set the value of variable h1 to another integer value
h1 = 5
推荐答案
我认为您想使用数据结构.如果您有成对或成组的值组合在一起,则创建一个可以容纳两者的派生数据类型.这个页面有说明:
I think you want to use a data structure. If you have pairs or groups of values that go together, then create a derived data type which can hold both. There's an explanation on this page:
http://web.mse.uiuc.edu/courses/mse485/comp_info/derived.html
如果您有这些对的列表(如上面的 string 和 int),那么您可以创建这些类型的数组.下面的示例代码取自上面链接的页面:
If you have a list of these pairs (like your string and int above), then you can create an array of these types. Example code below taken from the page linked above:
type mytype
integer:: i
real*8 :: a(3)
end type mytype
type (mytype) var
数组:
type (mytype) stuff(3)
var%i = 3
var%a(1) = 4.0d0
stuff(1)%a(2) = 8.0d0
这样做的一个显着好处是您可以将项目对/组一起传递给函数/子例程.这是一个重要的编程原则,称为封装,在面向对象编程范式中被广泛使用.
An significant benefit of doing this is that you can pass the pairs/groups of items to functions/subroutines together. This is an important programming principle called Encapsulation, and is used extensively in the Object Oriented programming paradigm.
这篇关于Fortran中根据字符串动态确定变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!