2

我正在研究 Metcalf、Reid 和 Cohen 的“现代 Fortran 解释”,在第四章中,它指定了一个斐波那契程序作为家庭作业问题。我下面的代码无法编译。我该如何纠正?

    !  Fibonacci here we go
    integer :: lim, i
    lim=0
    read *, lim

    integer, dimension(lim) :: fib

    if( lim >= 1 )
        fib(1) = 0
    end if

    if( lim >= 2 )
        fib(2) = 1
    end if

    if( lim >= 3 )
        fib(3) = 1
    end if

    do i=4, lim
        fib(i) = fib(i-2) + fib(i-1)
    end do

    do i=1, size(fib)
        print *, fib(i)
    end do

    end

另外,这是我遇到的错误。我会尝试将其缩短为所需的内容,但我不确定在查看 Fortran 错误日志时需要什么。

Compiling the source code....
$/usr/bin/gfortran /tmp/135997827718658.f95 -o /tmp/135997827718658 2>&1
In file /tmp/135997827718658.f95:7

integer, dimension(lim) :: fib
1
Error: Unexpected data declaration statement at (1)
In file /tmp/135997827718658.f95:9

if( lim >= 1 )
1
Error: Unclassifiable statement in IF-clause at (1)
In file /tmp/135997827718658.f95:10

fib(1) = 0
1
Error: Unclassifiable statement at (1)
In file /tmp/135997827718658.f95:11

end if
1
Error: Expecting END PROGRAM statement at (1)
In file /tmp/135997827718658.f95:13

if( lim >= 2 )
1
Error: Unclassifiable statement in IF-clause at (1)
In file /tmp/135997827718658.f95:14

fib(2) = 1
1
Error: Unclassifiable statement at (1)
In file /tmp/135997827718658.f95:15

end if
1
Error: Expecting END PROGRAM statement at (1)
In file /tmp/135997827718658.f95:17

if( lim >= 3 )
1
Error: Unclassifiable statement in IF-clause at (1)
In file /tmp/135997827718658.f95:18

fib(3) = 1
1
Error: Unclassifiable statement at (1)
In file /tmp/135997827718658.f95:19

end if
1
Error: Expecting END PROGRAM statement at (1)
In file /tmp/135997827718658.f95:22

fib(i) = fib(i-2) + fib(i-1)
1
Error: Statement function at (1) is recursive
Error: Unexpected end of file in '/tmp/135997827718658.f95'
4

1 回答 1

4

随机修复....

如果块应该是

if (condition) then
  do something
endif

不能省略“则”。

你不能去

read *, lim
integer, dimension(lim) :: fib

所有声明都必须在可执行代码之前。所以改为使用可分配数组

integer, dimension(:), allocatable :: fib
read *, lim
allocate(fib(lim))
于 2013-02-04T19:15:59.380 回答