2017-02-26 78 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