2017-02-26 79 views
2
 implicit real*8 (a-h,o-z) 
    real*8 x,y(11) 

    do i=0,10 
     x=0.35139534352933061.D0 
     y=1.D0/x*(cosh(x/2.D0*(2.D0*i-a))-cosh(x*a/2.D0)) 
     write(*,*) i,y(i) 
    end do 

你好,我想我的打印功能,y, 的值,因此我的程序应该打印y(0),y(1),y(2)...y(10)。但是由于在Fortran中,第一个元素是y(1)而不是y(0),Fortran将y(0)视为大数而不是第一个元素。如何在i=0时得到y的结果?如何将数组的默认边界从1降低到0?

我的第一次尝试是:

 implicit real*8 (a-h,o-z) 
    real*8 x,y(11) 

    do i=0,10 
     x=0.35139534352933061.D0 
     y=1.D0/x*(cosh(x/2.D0*(2.D0*i-a))-cosh(x*a/2.D0)) 
     y0=1.D0/x*(cosh(x/2.D0*(-a))-cosh(x*a/2.D0)) 
     y(0)=y0 
     write(*,*) i,y(i) 
    end do 

,但我得到以下警告:

警告:在(1)超出范围(0 < 1)的尺寸1

阵列参考

我对这个问题的解决方法:

do i=1,11 
    y=1.D0/x*(cosh(x/2.D0*(2.D0*(i-1)-a))-cosh(x*a/2.D0)) 
    write(10,*) i,y(i) 
    end do 

我只是改变了说法(i)(i-1)i=0,10i=1,11

+2

宣布为“真正的y(0:10)”。顺便说一下你的'y ='赋值是分配给整个数组的。 – agentp

+0

谢谢,那是解决方案。 –

回答

2

请不要做任何implicit以外implicit none。在使用隐式类型时,通过简单的拼写错误来创建难以调试的错误非常容易。虽然该数组边界将无法通过程序坚持要求

real :: x(0:10) 
real, dimension(-5:5, 2:17) :: y 

注:

您可以通过直接声明它们宣布与定制界限阵列

module test_bounds 

    implicit none 

contains 
    subroutine print_a(a) 
     integer, intent(in) :: a(:) 
     print*, 'w/o passed bounds:' 
     print*, 'lbound(a) : ', lbound(a, 1) 
     print*, 'ubound(a) : ', ubound(a, 1) 
    end subroutine print_a 

    subroutine print_a_bounds(a, start) 
     integer, intent(in) :: start 
     integer, intent(in) :: a(start:) 
     print*, 'w passed bounds:' 
     print*, 'lbound(a) : ', lbound(a, 1) 
     print*, 'ubound(a) : ', ubound(a, 1) 
    end subroutine print_a_bounds 
end module test_bounds 


program bounds 
    use test_bounds 
    implicit none 
    integer :: a(0:10) 
    integer :: i 

    a = (/ (i, i=0, 10) /) 

    print*, 'in main:' 
    print*, 'lbound(a) : ', lbound(a, 1) 
    print*, 'ubound(a) : ', ubound(a, 1) 


    call print_a(a) 
    call print_a_bounds(a, start=lbound(a, 1)) 

end program bounds 

输出:

in main: 
lbound(a) :   0 
ubound(a) :   10 
w/o passed bounds: 
lbound(a) :   1 
ubound(a) :   11 
w passed bounds: 
lbound(a) :   0 
ubound(a) :   10 
+0

有一件事情,如果数组越界,当它们通过,当它们没有通过时,它会定期困扰我。当我有真正的,DIMENSION(:),intent :: A,那么它似乎工作。这是密切的,因为我有一个插值并分配数组(0:(n + 1))...或者是可分配的细微差别? – Holmz

+0

我不知道这个工作。我相当肯定你需要在每个新的范围中明确声明边界,如果他们启动的地方不是'1'。 – chw21

+0

也许这就是为什么它“永远令人烦恼”?我正在使用ifort 2013所以我会检查它,但我使用的是LBOUND和UBOUND,它是正确的。 – Holmz