如何在Fortran中声明一个变量中间例程 [英] How to declare a variable mid-routine in Fortran

查看:295
本文介绍了如何在Fortran中声明一个变量中间例程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个基于满足另一个数组中特定条件的元素数量的维度的数组。这需要我初始化一个数组中程序,Fortran不会让我这样做。



有没有办法解决这个问题?

例程:

 子例程(some_array)

real some_array(50)!传递已知维数组

element_count = 0
do i = 1,50
if(some_array.gt.0)then
element_count = element_count + 1
endif
enddo

real new_array(element_count)!基于条件语句的新数组长度

endsubroutine示例

谢谢! / p>

解决方案

你的问题不是关于初始化数组,它涉及设置它的值。 >

然而,有一种方法可以做到你想要的。你甚至有选择,取决于它是多么普遍。



我假设 element_count 意味着在该循环中有一个 some_array(i)


$ b 您可以使 new_array allocatable
$ b

 子例程(some_array) 
real some_array(50)
real,allocatable :: new_array(:)

allocate(new_array(COUNT(some_array.gt.0)))
结束子程序

或者将它作为自动对象:

<
真实的some_array(50)
真正的new_array(COUNT(some_array.gt.0))
结束子程序

只有当您的条件是简单时,后者才起作用。 allocatable 情况更普遍,比如当你想使用完整循环而不是 count 内在时。



在这两种情况下,您都需要在可执行语句之前进行所有声明。



[As注意,在Fortran 2008下, block 构造允许自动对象,即使在可执行语句之后。]


I would like to create an array with a dimension based on the number of elements meeting a certain condition in another array. This would require that I initialize an array mid-routine, which Fortran won't let me do.

Is there a way around that?

Example routine:

subroutine example(some_array)

real some_array(50) ! passed array of known dimension

element_count = 0
do i=1,50
  if (some_array.gt.0) then
    element_count = element_count+1
  endif
enddo

real new_array(element_count) ! new array with length based on conditional statement

endsubroutine example

Thanks!

解决方案

Your questions isn't about initializing an array, which involves setting its values.

However, there is a way to do what you want. You even have a choice, depending on how general it's to be.

I'm assuming that the element_count means to have a some_array(i) in that loop.

You can make new_array allocatable:

subroutine example(some_array)
  real some_array(50)
  real, allocatable :: new_array(:)

  allocate(new_array(COUNT(some_array.gt.0)))
end subroutine

Or have it as an automatic object:

subroutine example(some_array)
  real some_array(50)
  real new_array(COUNT(some_array.gt.0))
end subroutine

This latter works only when your condition is "simple". The allocatable case is much more general, such as when you want to use the full loop rather than the count intrinsic.

In both of these cases you meet the requirement of having all the declarations before executable statements.

[As a side-note, under Fortran 2008 the block construct allows automatic objects even after executable statements.]

这篇关于如何在Fortran中声明一个变量中间例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆