You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fortran代码中已使用Go To命令时如何嵌套另一个Go To实现双层循环

你之前修改未达预期的核心原因有两个:

  1. 内层stations文件遍历完一次后,文件指针停在文件末尾,没有重置的话下次读取会直接触发结束条件,不会重新遍历内容
  2. 未正确调整跳转逻辑,原来的结束跳转直接终止程序,没有回到外层读取下一行event内容

按照要求用goto实现双层循环的修改后代码如下:

program events
        implicit none
        character*40 aline
        character*40 bline

        open (1, file="event", status="old")
        open (2, file="stations", status="old")
        open (3, file="output", status="new")

! 外层循环入口:每次读取一行event
20      read(1, '(a40)',end=60) aline
        ! 重置stations文件指针到开头,保证本次event行可以从头遍历所有站点
        rewind(2)
! 内层循环:遍历当前event对应的所有stations行
1       read(2, '(a40)',end=20) bline
        write(3,*) aline, bline
        go to 1

60      stop
end program events

修改说明:

  • 新增外层循环标签20作为event行的读取入口
  • 每次读取到一行event内容后,通过rewind(2)将stations文件的指针重置到文件头部
  • 将内层stations读取的结束跳转目标从60改为20:stations遍历完后回到外层读取下一行event,只有event文件全部读完触发结束条件时才会跳转到60终止程序

内容的提问来源于stack exchange,提问作者Sean Barnett Meyers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:39:01