在Fortran中确定循环后的循环控制变量的值 [英] Determining the value of a loop control variable after the loop in Fortran
问题描述
我有以下程序:
program example
implicit none
integer::i, x1
real::x(10)=0
do i=10,1,-2
x(10-i)=2*i+1
enddo
x1=i*2-1
end program example
我的问题是确定 x1
的值,但是由于从未输入或指定变量 i
,Fortran如何确定 i
用于计算 x1
?
My problem is to determine the value of x1
but since variable i
was never input or specified, how does Fortran determine the value of i
used in the calculation of x1
?
推荐答案
因为从未输入或指定变量 i
"
这个假设是错误的.在循环内, i
取精确定义的值10、8、6、4、2.
This assumption is wrong. Inside the loop i
takes exactly defined values 10, 8, 6, 4, 2.
循环结束后,Fortran标准指定 i
的值应为循环计数器的下一个值,就像循环仍在继续一样,因此 i 的值code>将为
0
.
After the loop finishes, the Fortran standard specifies that the value of i
shall be the next value of the loop counter as if the loop still continued, so the value of i
will be 0
.
因此 x1
的值将为0 * 2-1-= -1,可以通过在程序末尾添加 print *,x1
轻松地进行验证
So the value of x1
will be 0*2 - 1 = -1 and it can be easily verified by adding print *, x1
at the end of the program.
但是由于francescalus发现了您的程序存在另一个问题.在第一次迭代中, i
的值为10,并且您正在访问 x(0)
的 x(10-i)
.该元素不存在, x
仅具有从 x(1)
到 x(10)
的元素,因此访问 x(0)
是非法的,并且在此之后整个程序的行为是不确定的.
But there is a different problem with your program as francescalus found out. On the first iteration the value of i
is 10 and you are accessing x(10-i)
which is x(0)
. This element does not exist, x
has only elements from x(1)
to x(10)
so accessing x(0)
is illegal and the behaviour of the whole program after that point is undefined.
这篇关于在Fortran中确定循环后的循环控制变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!