【问题标题】:fortran code for comparing two sets of variables用于比较两组变量的 fortran 代码
【发布时间】:2020-06-11 08:17:59
【问题描述】:

我正在尝试获取一行数据,其中字符位置 21:28 是 x 值,字符位置 29:36 是 y 值。我想将这两组数字放在两个变量中并比较两者。然后如果 x

下面是我的代码,但是fortran学起来很困难,所以部分遗漏了。

program open
implicit none




call getarg(1,"block2.gro")
open(12,file="output.gro",status ='new')

Line =0
x = (21:28) !from input file to be x variable
y= (29:36)  !from input file to be y variable
row =       !unsure if I need a variable to contain the row
Line=line +1
    if (line .ne. 2) then
        if x < y
        write(12,*) row 
        line = line+1
        else 
        line=line +1
    end if

end program open

任何学习 fortran 的帮助或有用的地方都将不胜感激!

【问题讨论】:

  • fortran 很难学 噗,学C++ :-)
  • 我知道这个问题是关于 Fortran 的。然而,为模拟编写可靠的分析代码需要的不仅仅是语法。您是否考虑过使用专门用于读取此类文件的库?如chemfiles.org/chemfiles.f03/latest
  • 我会查看 chemfiles,也许这会让生活更轻松!

标签: fortran row


【解决方案1】:

当您学习一门新语言时,您需要慢慢开始。我有一种感觉,你试图一次做太多事情。

这里只是一些不起作用的东西:

  1. 您正在使用implicit none,这很好,您应该这样做。但是您没有声明任何变量。您使用了多个变量(linexyrow),但从不告诉编译器它们是什么类型。

  2. getarg 是一个返回命令行参数内容的子例程。这意味着您需要传递 character(len=&lt;something&gt;) 变量作为第二个参数,而不是常量。这将失败。

  3. 您永远不会真正打开输入文件或从中读取。

  4. x = (21:28) 的语法无效,但我想你知道。

  5. 我认为那里应该有一个循环,但没有。

顺便说一句,您甚至没有告诉我们 xy 是整数还是浮点值。

从文本文件中读取数字时,Fortran 实际上非常灵活。如果 x 和 y 是文本文件中唯一的数字,你可以这样做 read(&lt;unit&gt;, *) x, y:

program read_block
    implicit none
    real :: x, y
    integer :: ios

    open(unit=101, file='block2.gro', action='read', status='old')
    do
        read(101, *, iostat=ios) x, y
        if (ios /= 0) exit
        print *, x, y
    end do
    close(101)
end program read_block

如果其中有其他字符,您可能必须使用明确的格式:

read(101, '(20X, 2F8.3)', iostat=ios) x, y

或者,如果您仍然想要整行,则可以读取整行,然后从中提取 xy 的值:

real :: x, y
character(len=100) :: row     ! make sure that the length is sufficient to hold entire line
integer :: ios

...

read(101, '(A)', iostat=ios) row
if (ios /= 0) exit
read(row(21:28), *) x
read(row(29:36), *) y
...

我建议您尝试运行此代码,看看它做了什么,并使用您的谷歌技能继续并了解每一行的作用以及它为什么这样做。

【讨论】:

    猜你喜欢
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多