for-loop - 重新启动 do 循环

标签 for-loop fortran fortran90 restart

我有一个从 1 到 n 的 do 循环,其中包含一个 if 语句。 如果满足要求,则某些参数(包括n)会发生变化。 所以我想从i = 1再次开始整个do循环,直到i = n,直到不再满足要求并且i达到n。 但我不知道如何用 Fortran 编程。 因为在目前的情况下,do循环在if语句之后继续,如果接下来的i满足if语句,就会覆盖之前的数据。如果每次满足要求时 do-loop 都会重新启动,那么情况就不再是这样了。 有人知道如何在 fortran 90 中编程吗?

因此有一个包含一列数字的数组。如果满足 if 语句,我想在该列中插入一个额外的数字。因此,该点之前的所有数字都应保持不变,该额外点之后的所有点都应向下移动一位,然后在创建的空闲点中,额外的点就会出现。这一切都很好。 但是,如果if语句出现两次,则需要添加两个点,但是当需要添加第二个点时,它将覆盖第一个点添加的数据。因此,如果可以从第一次的结果(包括额外的点)开始,从头开始完全重新启动 if 循环,那么它将起作用。 因此,它应该从 i=1 开始,然后继续执行,直到满足 if 语句,执行 if 语句,在 i=1 处再次开始,并重复此操作,直到 i=n(每当一个点出现时,i=n 就会增加)添加) 我不明白代码有何相关性,但特别是对您而言: prevnumbers 是起始数字,经过一些步骤产生数字。如果 then 数字不满足 if 语句,则必须更改原始数字(prevnumbers),然后重新执行步骤。

do i = 1,n
    if (numbers(i,1) >= x) then
    !this part will transfer the previous numbers to the new numbers until the new point
        do j=1,i
            numbers(j,1)=prevnumbers(j,1)
        end do
        !This part will move the numbers after the new number one ahead so a free spot is created
        do j=n,i,-1
            numbers(j+1,1)=prevnumbers(j,1)
        end do
        !this part adds the new number and increases n by 1.
        numbers(i+1,1)=(prevnumbers(i,1)+prevnumbers(i+1,1))/2
        n=n+1
    end if
end do

最佳答案

如果您事先不知道确切的迭代次数,您可能不应该首先使用带有索引的 do 循环。未测试。

i = 0
do
   i = i + 1
   if (i>n) exit

    if (numbers(i,1) >= x) then
    !this part will transfer the previous numbers to the new numbers until the new point
        do j=1,i
            numbers(j,1)=prevnumbers(j,1)
        end do
        !This part will move the numbers after the new number one ahead so a free spot is created
        do j=n,i,-1
            numbers(j+1,1)=prevnumbers(j,1)
        end do
        !this part adds the new number and increases n by 1.
        numbers(i+1,1)=(prevnumbers(i,1)+prevnumbers(i+1,1))/2
        n=n+1
    end if
end do

关于for-loop - 重新启动 do 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22782119/

相关文章:

c# - 循环碰撞逻辑错误

linux - Bash for 循环 - 列出/etc/init.d 中的文件,然后对结果运行命令

c++ - 优化for循环的函数调用

arrays - 从 Fortran 中的子例程返回分配的字符串数组?

linux - 我是否必须使用 -fPIC 来创建共享对象库?

module - Fortran 模块中的格式化语句

fortran - 错误#6451 : A dummy argument name is required in this context

c - 对带有数组和嵌套 For 循环的程序中特定语句的作用感到困惑

arrays - Fortran 中分配的字符串数组的段错误

fortran - 使用 kind 参数声明类型时出错