Fortran子程序未返回预期值

人工智能 2026-07-08

下面的Fortran程序中,我试图根据月份编号构建一个月份名称缩写的数组。我输入一个月份编号,然后立即调用一个子程序将数字转换为缩写。调用子程序后,缩写仍然为空,尽管没有错误。我是在网上搜索时得到这段代码的。因为搜索结果只给了一个AI摘要,所以我无法提供原始来源的帖子。

     program Process_MonthNum2Abbr
     implicit none

     integer :: input_val
     integer :: count
     integer :: my_month
     character(len=3) :: my_abb

     integer, allocatable, dimension(:) :: numbers
     integer, allocatable, dimension(:) :: temp_numbers

     !Initialize
     count = 0
     allocate(numbers(0))

     print *, "Enter a month to process - 1 for Jan, or more than one month, one by one (type '99' to stop):"

     !Loop to continuously prompt and read values
     do
        read(*, *) input_val

        if(input_val < 1 .or. input_val > 12) then
           print*,"Invalid Entry for Month, Try again"
        endif

        !Check for the sentinel value to exit the loop
        if(input_val == 99) exit

        count = count + 1

        call num_to_month(input_val, my_abb)
        print*, "Month ", input_val, " is ", my_abb
        stop
     enddo
    end program Process_MonthNum2Abbr

  subroutine num_to_month(month_num, month_abb)
  implicit none

     !Inputs and Outputs
     INTEGER, INTENT(IN) :: month_num
     CHARACTER(LEN=3), INTENT(OUT) :: month_abb

     ! Lookup table for abbreviated months
     CHARACTER(LEN=3), DIMENSION(12), PARAMETER :: months = &
        [CHARACTER(LEN=3) :: "Jan", "Feb", "Mar", "Apr", "May", "Jun", &
                             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
     print*,month_num,"abbr",month_abb !(prints month-num correctly, abbr and no month_abb)
     stop
    return
   end subroutine num_to_month

解决方案

调用子程序后,缩写仍然为空,尽管没有错误。

是的,因为该函数从未修改 month_abb 的值。也许你本来想在 print 语句之前包含如下内容:

    month_abb = months(month_num)

附注:99大于12,因此当用户输入99以结束程序时,他们将首先看到 "Invalid Entry for Month, Try again" 的提示信息。你可以通过先对99进行测试并在满足条件时退出来避免这种情况。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章