如何将数组的默认边界从1降低到0?

时间:2017-02-26 12:41:44

标签: loops fortran

     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)视为一个大数而不是第一个元素。如何在y

时获得i=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,10更改了i=1,11

1 个答案:

答案 0 :(得分:2)

除了implicit之外,请不要执行任何implicit none。当你使用隐式类型时,很容易通过简单的拼写错误来调试bug。

您可以通过直接声明数组来声明具有自定义边界的数组:

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
相关问题