我如何让循环计数器不会大于最终值? [英] How can I make the loop counter not be greater than the final value?

查看:182
本文介绍了我如何让循环计数器不会大于最终值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

给我 2 作为 i 的最终值。如何在Windows上为Visual Studio设置英特尔Fortran,以便为 i ?提供最终值 1 / p>

解决方案

你不行,因为这就是DO的工作原理;当控制变量超出限制时停止。

一般来说,在几乎所有使用FOR / DO计数循环的语言中,只能在循环体内使用循环控制变量,并将其视为在别处未定义,即使你实际上不能将其范围限制在body中。



在你的情况中,我将使用一个不同的变量来跟踪i的实际最后值在任何迭代中:

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


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 Fortran for Visual Studio on Windows to give me a final value of 1 for i?

解决方案

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

这篇关于我如何让循环计数器不会大于最终值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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