Fortran:在函数中调用其他函数

时间:2016-07-23 18:24:02

标签: function fortran gfortran

我在Code :: Blocks上的两个单独的文件中编写了GNU Fortran代码:main.f95,example.f95。 main.f95内容:

program testing

   use example

   implicit none
   integer :: a, b

   write(*,"(a)", advance="no") "Enter first number: "
   read(*,*) a

   write(*,"(a)", advance="no") "Enter second number: "
   read(*,*) b

   write(*,*) factorial(a)
   write(*,*) permutation(a, b)
   write(*,*) combination(a, b)

end program testing

example.f95内容:

module example


contains


  integer function factorial(x)

     implicit none
     integer, intent(in) :: x
     integer :: product_ = 1, i

     if (x < 1) then

        factorial = -1

     else if (x == 0 .or. x == 1) then

        factorial = 1

     else

        do i = 2, x
           product_ = product_ * i
        end do

        factorial = product_

     end if

  end function factorial


  real function permutation(x, y)

     implicit none
     integer, intent(in) :: x, y
     permutation = factorial(x) / factorial(x - y)

  end function permutation


  real function combination(x, y)

     implicit none
     integer, intent(in) :: x, y

     combination = permutation(x, y) / factorial(y)

  end function combination


end module example

当我运行此代码时,输​​出为:

Enter first number: 5
Enter second number: 3
     120
   0.00000000    
   0.00000000    

排列和组合功能无法正常工作。谢谢你的回答。

1 个答案:

答案 0 :(得分:2)

我认为你已经对Fortran的知名人士(对那些知道它的人)感到厌恶。但在揭露之前我必须问你做了多少测试?我跑了你的代码,得到了奇怪的结果,想了一会......

然后我测试了factorial函数的几个小x生成的值

 factorial            1  =            1
 factorial            2  =            2
 factorial            3  =           12
 factorial            4  =          288
 factorial            5  =        34560
 factorial            6  =     24883200
 factorial            7  =    857276416
 factorial            8  =   -511705088
 factorial            9  =   1073741824
 factorial           10  =            0

这显然是错误的。因此,在寻求帮助之前,您似乎没有正确测试代码(如果有的话)。 (我没有测试您的combinationpermutation功能。)

O tempora,o mores

您已在行

中初始化变量product_
 integer :: product_ = 1, i

这自动意味着product_获取属性save,因此其值从调用存储到调用(gotcha!)。在每次通话开始时({1}除外)product_具有上一次通话结束时的值。

补救措施很简单,不要初始化product_。改变

 integer :: product_ = 1, i

 integer :: product_ , i
 ...
 product_ = 1

更简单的仍然是不要编写自己的阶乘函数,而是使用内在的product函数,但这是另一个故事。

相关问题