How can I make the loop counter not be greater than the final value?

后端 未结 2 1725
猫巷女王i
猫巷女王i 2021-01-19 05:57

So sample loop:

do i=1,1
    print *,i
enddo
print *,i

gives me 2 as the final value of i. How can I set up Intel

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 06:36

    You can't, because that's how DO works; it stops when the control variable exceeds the limit.

    In general, in pretty much any language with a FOR/DO counting loop, you should only use the loop control variable inside the loop body, and treat it as undefined elsewhere, even if you can't actually limit its scope to the body.

    In your case, I would use a different variable to keep track of the actual last value of i in any iteration:

    lasti = 0
    do i=1,1
       print *,i
       lasti = i
    enddo
    print *,lasti
    

提交回复
热议问题