通过添加更新Fortran变量 [英] Updating a Fortran variable by addition
问题描述
在我的Fortran代码中,我需要通过添加一些变量来更新许多变量.例如,如果 x
是我的变量,则可能需要执行以下操作:
In my Fortran code I need to update many variables by adding something to them. For example, if x
is my variable, I may need to do something like this:
x = x + 1
问题在于我的变量是数组元素,并且具有大的名称等,因此在上述等式中重复 x
是一项繁琐的任务.例如,在Python中,我们可以使用 + =
运算符来实现此目的.我们在Fortran中有类似的东西吗?
The problem is that my variables are array elements and have big names etc so repeating x
in the above equation is cumbersome task. In Python for example we have the +=
operator to achieve this. Do we have something similar in Fortran?
推荐答案
否,Fortran没有此运算符.但是,您可以实现一个子例程来完成此操作:
No, Fortran does not have this operator. However, you could implement a subroutine to do so:
elemental subroutine my_incr( var, incr )
implicit none
integer,intent(inout) :: var
integer,intent(in) :: incr
var = var + incr
end subroutine
然后您可以在代码中调用它:
Then you could call that in your code:
! ...
call my_incr( x, 1 )
! ...
由于子例程的 elemental
性质,您还可以在数组上执行此操作:
Due to the elemental
nature of the subroutine, you can also perform this operation on arrays:
! ...
call my_incr( array(:), 1 )
! ...
这篇关于通过添加更新Fortran变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!